What Is ContentChildren in Angular?

ContentChildren explained with an example

Deepak Pandey
Oct 17, 2019 · 2 min read

What Is ContentChildren?

ContentChildren is a parameter decorator that is used to fetch the QueryList of elements or directives from the content DOM. The QueryList is updated whenever the child element/component is added or removed.

The child element reference is set in QueryList just before the ngAfterContentInit lifecycle Hook method.

Below, we are using the ContentChildren to get the QueryList containing the list of the child component ChildComp. The list is stored in the contentChildren variable in the Parent component.

Let’s see an example that utilizes the power of ContentChildren

We are creating a child component TabComponent with an input property object tab and a function that prints the title property of the tab object. The template just displays the properties.

TabListComponent is the parent component where we are accessing the child component TabComponent list from the content DOM using the ContentChildren decorator.

As the child element references are set in QueryList just before the ngAfterContentInit callback, we are accessing the QueryList in the ngAfterContentInit lifecycle Hook.

In the template, we are using the ng-content directive which projects the elements in between the <app-tab-list><app-tab-list> tag to the component’s view.

The elements added between the selector element are said to be content-projected elements and are accessible by ContentChildren.

As you can see, we are able to access the child component method from the parent component (as shown in the ngAfterContentInit method).

Finally, this is the top view component with the above two selectors in its template.

Note: If we have a single child content element then we can use ContentChild instead of ContentChildren.

Better Programming

Advice for programmers.

Deepak Pandey

Written by

Angular | Vue | Angular JS | JavaScript | Python | Java

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade