Angular View Children and Content Children

technologytutorialangular
by

Dimitar Stoev

ViewChild && ViewChildren

template variables are visible only in the HTML and not the components

In order to have access to template variables we use the "@ViewChild('name_of_variable')". The viewChild is an ElementRef and it doesn't have direct access to the element, but the nativeElement has.

In order to get the ChildComponent, the syntax is:

In order to have access to all references we have to wait until the view is initialized. The life cycle hook that is used is ngAfterViewInit

@ViewChildren('name_of_variable_one','name_of_variable_two')

It is important to keep the template variables without space between the coma

QueryList<T> - this is a generic class. We can pass reference as ElementRef or any other component

QueryList contains a changes property, which is an Observable. We can subscribe() to it to be notified of changes to the list. Another point to make is an ordered list!

The list that is generated with the @ViewChildren is a dynamic one, so any update on the children is going to reflect on the list.

Content Child && Content Children

Content children come from another component's view/template.

@ContentChild and @ContentChildren are often used when implementing expand/collapse components such as tabs, accordions and menus.

In the Angular documentation we read that

ContentChild gets the first element or the directive matching the selector from the content DOM. If the content DOM changes, and a new child matches the selector, the property will be updated.

Another thing to point out is

Content queries are set before the ngAfterContentInit callback is called.

More from this category