Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: @ContentChild - only immediate children

Tags:

angular

So for better illustration will simplify and try to be as concise as possible.

<my-accordion>
    <my-title>My accordion</my-title>

    <my-accordion-item>
        <my-title>My accordion item 1</my-title>
        <my-content>Content 1</my-content>
    <my-accordion-item>
    <my-accordion-item>
        <my-title>My accordion item 2</my-title>
        <my-content>Content 2</my-content>
    <my-accordion-item>
</my-accordion>

As you can see, I use (my) standard my-title for my-accordion and my-accordion-item

So in my-accordion component I have the logic

private title:string = '';
@ContentChild( myTitle ) myTitle: myTitle;

ngAfterViewInit(){
    if(this.myTitle && this.myTitle.content.length !== 0){
        this.title = this.myTitle.content;
    }
}

So, if I had my view exactly like in my previous example, it works OK.... and the title coming back is "My accordion" but, if I don't have the my-title element on the root of my-accordion....like this:

<my-accordion>        
    <my-accordion-item>
        <my-title>My accordion item 1</my-title>
        <my-content>Content 1</my-content>
    <my-accordion-item>
    <my-accordion-item>
        <my-title>My accordion item 2</my-title>
        <my-content>Content 2</my-content>
    <my-accordion-item>
</my-accordion>

The title would be set to "My accordion item 1", because it gets the first my-title in the whole DOM sub tree

Is there a way to just check immediate children?

like image 371
DS_web_developer Avatar asked Mar 09 '23 23:03

DS_web_developer


1 Answers

@ContentChild() doesn't but @ContentChildren() does https://angular.io/docs/ts/latest/api/core/index/ContentChildren-decorator.html

@ContentChildren( myTitle, {descendants: false}) myTitle: QueryList<myTitle>;

ngAfterContentInit() {
  console.log(this.myTitle.toArray()[0]);
}

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

like image 83
Günter Zöchbauer Avatar answered Mar 20 '23 19:03

Günter Zöchbauer