@viewChild: When we want to access child component , directive & DOM element inside the parent component then viewchild can be used.
counter-child.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-counter-child',
templateUrl: './counter-child.component.html',
styleUrls: ['./counter-child.component.css']
})
export class CounterChildComponent implements OnInit {
message:string;
count= 0;
constructor() { }
ngOnInit(): void {
}
increaseByOne(){
this.count = this.count + 1;
this.message = 'Count value is' + ' ' + this.count;
}
deacreaseByOne(){
this.count = this.count - 1;
this.message = 'Count value is ' + ' ' + this.count;
}
}
counter-child.component.html:
<p>{{message}}</p>
counter-parent.component.html:
<p>This is @viewChild example</p>
<div>
<button class="btn btn-primary m-1" (click)="increase()">Increase</button>
<button class="btn btn-primary" (click)="decrease()">Decrease</button>
</div>
<app-counter-child></app-counter-child>
counter-parent.component.ts:
import { Component, OnInit, ViewChild } from '@angular/core';
import { CounterChildComponent } from '../counter-child/counter-child.component';
@Component({
selector: 'app-counter-parent',
templateUrl: './counter-parent.component.html',
styleUrls: ['./counter-parent.component.css']
})
export class CounterParentComponent implements OnInit {
@ViewChild(CounterChildComponent) counter: CounterChildComponent;
constructor() { }
ngOnInit(): void {
}
increase(){
this.counter.increaseByOne();
}
decrease(){
this.counter.deacreaseByOne();
}
}
No comments:
Post a Comment