如何从父组件调用子组件的功能

Вик*_*шев 0 communication parent-child typescript angular

就是看不懂

单击父组件中的按钮时如何调用子组件中的函数?

Sre*_*r P 6

使用@ViewChild装饰器来访问您的子组件。

import { ChildComponent } './child.component'
import { ViewChild } from '@angular/core';

export class ParentComponent {

  @ViewChild(ChildComponent)
  childComponent: ChildComponent;

  someMethod() {
     this.childComponent.someFunction();
  }
}
Run Code Online (Sandbox Code Playgroud)


Pie*_*Duc 6

如果这是您的父模板:

<button (click)="onClick()">Click</button>
<div>
  <child-component></child-component>
</div>
Run Code Online (Sandbox Code Playgroud)

@ViewChild()您可以在父级中使用:

export class ParentComponent {
  @ViewChild(ChildComponent)
  child: ChildComponent;

  onClick(): void {
    if (this.child) {
      this.child.someFunction();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是直接在模板中执行此操作:

您可以将模板更改为:

<button (click)="child.someFunction()">Click</button>
<div>
  <child-component #child></child-component>
</div>
Run Code Online (Sandbox Code Playgroud)

那么就不需要使用@ViewChild了。如果您需要在单击中执行其他操作,您甚至可以将子变量传递给父级内部的函数