ViewChildren passing multiple components

2020-06-19 08:48发布

问题:

Why can't I pass multiple components within the @ViewChildren?

Currently have this:

 @ViewChildren(ColorFilterComponent, TransmissionFilterComponent)
 public filters: QueryList<Filter>;

Both components implements my Filter interface:

export declare abstract class Filter {
    abstract applyFilter(vehicles: Vehicle): boolean;
}

At a certain point I am iterating through filters and calling applyFilter() method for all components within the viewChildren.

However when I do a simple log:

console.log(this.filters.toArray());

It contains only one filter. The other one is not here.

What would be a good best practice in this case?

回答1:

HTML:

 <colorfilter #filter></as-colorfilter>
 <transmissionfilter #filter></as-transmissionfilter>

Component:

@ViewChildren('filter')
public filters: QueryList<Filter>;


回答2:

This is only supported with template variables

@ViewChildren('var1,var2,var3')

but not with component or directive types.

If Filter is a common base class, you can try something like:

providers: [{ 
  provide: Filter, 
  useExisting: [ColorFilterComponent, TransmissionFilterComponent],
  multi: true
}]

and then query like

@ViewChildren(Filter) filters: QueryList<Filter>;

See also https://github.com/angular/angular/issues/8580#issuecomment-218331920



标签: angular