child.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent { // 子组件的方法 alert(d: any) { alert(d); } }
app.component.ts
import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './com/child/child.component'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { @ViewChild('child') child: ChildComponent | undefined;//获取子组件对象 childAlert(text: any) { this.child?.alert(text);//父组件调用子组件的方法 } }
app.component.html
<app-child #child></app-child> <button (click)="childAlert('调用子组件的方法')">调用子组件的方法</button>