Conclusion. The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.
The ViewChild or ViewChildren decorators are used to Query and get the reference of the DOM element in the Component. ViewChild returns the first matching element and ViewChildren returns all the matching elements as a QueryList of items. We can use these references to manipulate element properties in the component.
We can use the @ViewChildren decorator to grab elements from the host view. The @ViewChildren decorator supports directive or component type as parameter, or the name of a template variable. When the parameter is a component/directive the return value will be the component/directive instance.
Use @ViewChildren
from @angular/core
to get a reference to the components
template
<div *ngFor="let v of views">
<customcomponent #cmp></customcomponent>
</div>
component
import { ViewChildren, QueryList } from '@angular/core';
/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
l̶i̶v̶e̶ ̶d̶e̶m̶o̶
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
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