Angular / Basics / Call child function from parent component
Call child function from parent component
-
Solution 1 : using #child
Step1: in child component
import { Component } from '@angular/core'; Component({ selector: 'child', template: ` Child component {test}
`, }) export class ChildComponent { test = 0; callMethod() { console.log('successfully executed.'); this.test++; } ... }Step 2: in parent component
import { Component } from '@angular/core'; Component({ selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent { constructor() { } ... } Step3: in parent html
-
Solution 2: using @ViewChild
Step1: in child component
Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { callMe(value : string) { console.log('Called : ' + value); } .... } Step2: in parent component
export class ParentComponent implements OnInit { @ViewChild(ChildComponent, {static : true}) child : ChildComponent; callMyChild(){ child.callMe('Calling from the parent!'); } .... } Step3: in parent html