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?
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With