ViewChild allows a one component to be injected into another, giving the parent access to its attributes and functions. One caveat, however, is that child won’t be available until after the view has been initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.
Child Component
There is no change in the child component
Parent Component
In parent component, we need to import the viewChild annotation. We also need to import the child component
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<p> current count is {{child.count}} </p>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>
<child-component></child-component>` ,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Parent calls an @ViewChild()';
@ViewChild(ChildComponent) child: ChildComponent;
increment() {
this.child.increment();
}
decrement() {
this.child.decrement();
}
}
Child Component
There is no change in the child component
Parent Component
In parent component, we need to import the viewChild annotation. We also need to import the child component
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<p> current count is {{child.count}} </p>
<button (click)="increment()">Increment</button>
<button (click)="decrement()">decrement</button>
<child-component></child-component>` ,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Parent calls an @ViewChild()';
@ViewChild(ChildComponent) child: ChildComponent;
increment() {
this.child.increment();
}
decrement() {
this.child.decrement();
}
}
No comments:
Post a Comment