简体   繁体   中英

How to call a method of child component from parent component

I am having two components in parent child relationship I am sending the data to a child component from a parent component based on the selected options of the mat-select. If a user selects the second option from a mat-select I want to clear the previous displayed value and show the new values based on the selected option. To achieve this I have to call a method from child component into parent component. Could anyone please tell me how I can achieve this

You can call child component method from parent using @ViewChild .

Stackblitz Demo

parent.component.ts

import { Component, ViewChild } from "@angular/core";
import { ChildComponent } from "./child.component";

@Component({
  selector: "my-app",
  template: `
    <child name="{{ name }}"></child>
    <button (click)="onClick()">Call Child method</button>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  name="Hello";
  @ViewChild(ChildComponent) ChildComponent;

  onClick() {
    this.ChildComponent.childMethod();
  }
}

Child Component

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

@Component({
  selector: 'child',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class ChildComponent  {
  @Input() name: string;

  childMethod(){
    alert('childMethod')
  }
}

This can be done using @ViewChild . Consider this below example:-

Parent.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from '../child/child'; 
@Component({ 
           selector: 'parent-app', 
           template: `<child-cmp></child-cmp>` 
          }) 
export class parentComponent implements OnInit{ 
    @ViewChild(ChildComponent ) child: ChildComponent ; 

    ngOnInit() { 
       this.child.childCompFunction(); } 
}

Child.component.ts

import { Component } from '@angular/core';
@Component({ 
  selector: 'child-cmp', 
  template: `<h2> Show Child Component</h2><br/><p> {{test}}</p> ` 
})
export class ChildComponent {
  test: string;
  childCompFunction() 
  { 
    this.test = "I am child component!"; 
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM