Property decorator that configures a view query
View queries are set before the ngAfterViewInit callback is called.
import { Component, OnInit,AfterViewInit, viewChild } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit, AfterViewInit {
constructor() { }
@ViewChild('addBtn') addBtn:ElementRef;
ngOnInit(): void {
}
ngAfterViewInit() {
// child is set
console.log(this.addBtn.nativeElement)
}
}
<button #addBtn>add</button>
…………………………………………………………………………………………………………………………………….
@viewchildren
@viewchildren decorator returns the list of different native DOM elements through og QueryList
@ViewChild() in a component can communicate with another component or a directive.
But if we want to access multiple child references, then we have to use @ViewChildren.
import {AfterViewInit, ElementRef, viewChildren,QueryList} from '@angular/core'
export class AppComponent implements AfterViewInit {
// Accessing multiple native DOM elements using QueryList
@ViewChildren(HelloComponent) myValue: QueryList<HelloComponent>;
ngAfterViewInit() {
console.log("Hello ", this.myValue.toArray(););
}
}
<hello name="{{ name }}"></hello>
<hello name="{{ name }}"></hello>
<hello name="{{ name }}"></hello>