在 Angular 中,父组件可以通过子组件的输入属性 (@Input()) 将方法传递给子组件。

  1. 在子组件的类中,定义一个输入属性来接收父组件传递的方法:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `...` // 子组件的模板
})
export class ChildComponent {
  @Input() methodFromParent: Function;

  // 子组件中可以调用这个方法
  callMethodFromParent() {
    if (this.methodFromParent) {
      this.methodFromParent();
    }
  }
}
  1. 在父组件的模板中,使用子组件并将方法传递给子组件的输入属性:
<app-child [methodFromParent]="parentMethod"></app-child>
  1. 在父组件的类中,定义一个方法作为父组件要传递给子组件的方法:
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `...` // 父组件的模板
})
export class ParentComponent {
  parentMethod() {
    // 这个方法会被子组件调用
  }
}

这样,父组件就可以将自己的方法传递给子组件,并通过子组件的方法调用父组件的方法。

Angular 父组件传递方法给子组件

原文地址: https://www.cveoy.top/t/topic/e2TL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录