Contentchild Decorator Angular Angular

Jul 3rd, 2020 - written by Kimserey with .

Continuing on our discovery of Angular decorators, in this week post we will be looking at ContentChild and ContentChildren. What the differences are, and when to use one or another.

ContentChild

ContentChild is a decorator which allows us to get access to an element in the content of the component or directive.

The content is the DOM contained within the component. For example, in the following template,

1
2
3
<app-hello-world>
  <div #test>Some content</div>
</app-hello-word>

the app-hello-world component has the div as content. Hence ContentChild can be used in AppHelloWorld to get a reference on the div.

1
2
3
4
5
6
7
8
9
10
11
@Component({
  selector: 'app-hello-world',
  template: 'hello world'
})
export class AppHelloWorld implements AfterContentInit  {
  @ContentChild('test') content: ElementRef;

  ngAfterContentInit() {
    // content is accessible from here.
  }
}

The benefit of ContentChild is gives control to the user of the directive to provide templates to be used then in the component.

In the same way as ViewChild, it is possible to select the element by component or directive types or use a template reference. But as opposed to ViewChild which would allow access to an element in the template of the component or directive.

ContentChildren

Just like ViewChild and ViewChildren, ContentChild has an equivalent decorator to select multiple elements, ContentChildren. For example if we have the following template:

1
2
3
4
5
<app-hello-world>
  <div #test>Some content</div>
  <div #test>Some content</div>
  <div #test>Some content</div>
</app-hello-word>

we can select all content children using ContentChildren:

1
@ContentChildren('test') children: QueryList<ElementRef>;

In our previous post on ViewChild, we discussed QueryList which work in the same way here.

And that concludes today’s post!

Conclusion

In today’s post, we looked into ContentChild and ContentChildren. We saw how ContentChild was used to query elements in the content of the component. We saw what we called the content which is the DOM specified between the component tag. And we ended the post by looking at how to query multiple elements with ContentChildren. I hope you liked this post and I see you on the next one!

External Sources

Designed, built and maintained by Kimserey Lam.