ViewChildren passing multiple components

Why can't I pass multiple components to @ViewChildren?

Currently it is:

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

Both components implement my filter interface:

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

At some point, I repeat through filtersand calling the method applyFilter()for all components in viewChildren.

However, when I make a simple log:

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

It contains only one filter. There is no other here.

What would be good good practice in this case?

+4
source share
2 answers

HTML:

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

component:

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

This is only supported using template variables.

@ViewChildren('var1,var2,var3')

but not with components or directory types.

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

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

and then run the query as

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

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

+3

Source: https://habr.com/ru/post/1653890/


All Articles