问题
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.
回答1:
@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?
回答2:
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>
来源:https://stackoverflow.com/questions/40233844/angular2-querylist-based-on-element-class