Call method of child component in parent component Angular 8

Dung Do Tien Nov 16 2020 57

I have two components in Angular 8:

Child component

import { Component } from '@angular/core';

@Component({
  selector: 'child-component',
  template: `<h2>Child component</h2>`
})
export class ChildComponent {
  callMethod() {
    console.log('call method of child component');
  }
}

Parent component

@Component({
  selector: 'parent-component',
  template: '<div> <child-component></child-component> <button (click)="submit()">Call</button> <div>',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  submit() {
    // Call method of child component HERE
  }
}

Now I want to call callMethod() method of child component inside submit() method of the parent component. 

Please support me if you know any solution.

Have 2 answer(s) found.
  • You can use @ViewChild in parent component like in example:

    import { Component, ViewChild } from '@angular/core';
    import { ChildComponent } from './child.component';
    
    @Component({
      selector: 'parent-component',
      template: '<div> <child-component></child-component> <button (click)="submit()">Call</button> <div>',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      @ViewChild(ChildComponent, {static: true}) private myChild: ChildComponent;
      constructor() { }
      submit() {
        // Call method of child component HERE
    	myChild.callMethod();
      }
    } 
    

    If your version angular in your project is less then 8 you have to change:

    @ViewChild(ChildComponent, {static: true}) private myChild: ChildComponent; 
    

    to

    @ViewChild(ChildComponent) private myChild: ChildComponent; 
    
    Sandeep Kumar Nov 17 2020
  • In a simple way, you can call directly the child component method from Html with an alias. You can see code below:

    @Component({
      selector: 'parent-component',
      template: '<div> <child-component #childcomponent></child-component> <button (click)="childcomponent.callMethod()">Call</button> <div>',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      constructor() { }
    } 

    This way working for me. 

    Manish Kumar Nov 17 2020
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips