1.

What are the differences between @ViewChild and @ViewChildren decorators in Angular?

Answer»

@ViewChild decorator is used to SEARCH for an element inside the component’s template. It makes it very easy to GET a reference to a child component from the template. The parameter that we pass as the first argument to the ViewChild is the type of the component or the reference we want to search for, in the template. If more than ONE elements match the queried elements, it returns us the first one that it found. @ViewChild returns a reference of an element so, we can use ElementRef to define the type of variable.

To get references to MULTIPLE children components we can use @ViewChildren() decorator. It returns a QueryList object that is an array of the references to the matches elements in the template.

Example: Consider the following HTML snippet in a component.

<some-component #someVariable></some-component>

To get a reference to the component in the component class, we can use @ViewChild. All we NEED to do is,

@ViewChild('someVariable') something;

Similarly, if you want to get access to all the elements of the page that have certain type, you can do that using,

@ViewChildren(someType) somethings;

This returns a QueryList which is an array of the references to all the matching elements.



Discussion

No Comment Found