How to trigger/access the child component method from parent component
We can do this by using @ViewChild.
Reference : https://angular.io/guide/component-interaction
Stackblitz demo : https://stackblitz.com/edit/angular-child-method-access?file=src/app/app.component.ts
Way 1) With type selector
Parent component:
export class ParentComponent implements OnInit {
//Type selector
@ViewChild(ChildComponent) childComp: ChildComponent;
constructor() {}
ngOnInit() {}
parentClickEvent() {
this.childComp.childMethod();
}
}
Child Component:
export class ChildComponent implements OnInit {
childMethodStatus = "Child Method not trigered";
count = 0;
constructor() {}
ngOnInit() {}
childMethod() {
this.count = this.count + 1;
this.childMethodStatus = "Child Method trigered " + this.count;
}
}
Way 2) With string selector
Parent component - TS:
export class ParentComponent implements OnInit {
//String selector
@ViewChild('child') childComp: ChildComponent;
constructor() {}
ngOnInit() {}
parentClickEvent() {
this.childComp.childMethod();
}
}
Parent Component - Html
<app-child #child></app-child>
Child Component:
export class ChildComponent implements OnInit {
childMethodStatus = "Child Method not trigered";
count = 0;
constructor() {}
ngOnInit() {}
childMethod() {
this.count = this.count + 1;
this.childMethodStatus = "Child Method trigered " + this.count;
}
}
Happy Coding...😉
Comments
Post a Comment