Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 869
Meir Avatar asked Oct 25 '16 07:10

Meir


2 Answers

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>
like image 180
Eliseo Avatar answered Oct 27 '22 20:10

Eliseo


@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?

like image 27
Günter Zöchbauer Avatar answered Oct 27 '22 22:10

Günter Zöchbauer