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.
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.
Share Improve this question edited Oct 25, 2016 at 7:30 Günter Zöchbauer 657k232 gold badges2.1k silver badges1.6k bronze badges asked Oct 25, 2016 at 7:27 MeirMeir 14.4k4 gold badges44 silver badges48 bronze badges2 Answers
Reset to default 10@ViewChild()
, @ViewChildren()
, @ContentChild()
, @ContentChildren()
only support the name of a template variable (or a comma separated list of names) or the types of components or directives as selectors as it is also mentioned in angular documentation.
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 How can I select an element in a component template?
It's an old question, but thanks to this link about carousel by Netanet Basal are a work around about the question.
If we write a simple directive, that has as selector a className -in the e.g. class "myClass", -you can add in the same .ts that your component, but don't forget declare in your module-
@Directive({
selector: '.myClass'
})
export class MyClassElement {
}
Make possible has some like
@ViewChildren(MyClassElement , { read: ElementRef })
private itemsElements : QueryList<ElementRef>;
In an .html
<div class="myClass">one</div>
<div class="myClass">two</div>
<div class="myClass">three</div>