Call child function from parent component

  • Solution 1 : using #child

    Step1: in child component
    
    
    
                      import { Component } from '@angular/core';
    
                        Component({
                            selector: 'child',
                            template: `<h3>Child component {test}</h3>`,
                        })
                        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
    
    
    
                                <button (click)="child.callMethod()" >Call Child Component Method</button>
                                <child #child></child>
    
    
    
                            

  • 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
    
                            <app-child></app-child>