Meir Meir - 1 month ago 31
HTML Question

Angular2 QueryList based on element class

Is there a way to retrieve

ViewChildren
or
ContentChildren
by element class?

This will work, either by id or component but not for the class based queries, namely
classedViewItems
and
classedContentItems


@Component({
selector: 'my-container',
template '<div><ng-content><ng-content></div>'
})
export class MyContainer {
@ViewChildren('item') viewItems: QueryList;
@ContentChildren(MyItem) contentItems: QueryList;
@ViewChildren('.fine-me') classedViewItems: QueryList; // <-- need this to work
@ContentChildren('.find-me') classedContentItems: QueryList; // <-- or this
}


for the following:

<my-container>
<my-item class="find-me" #item *ngFor="let item; of items"></my-item>
</my-container>


I need to get the query list by the element class without decorating it.

Answer

@ViewChild(), @ViewChildren(), @ContentChild(), @ContentChilden() only support the name of a template variable (or a comma separated list of names) or the types of components or directives as selectors.

There is no way to use other selectors. What you can do is to filter QueryList afterwards to only get the elements with a specific class but that doesn't free you from adding a template variable to each of them.

See also angular 2 / typescript : get hold of an element in the template

Comments