首页 > 解决方案 > 在父级调用方法并从子级获取返回值

问题描述

我的目标是,从子组件中,我想在父组件中调用一个方法并获取返回值。我尝试了以下方法,但没有成功。

在 parent.html 中

<child-component [config]="getConfig(data)"></child-component>

在 parent.ts

data = <some data>
...
getConfig(val) {
    // format value and return
    return formattedVal;
}

在 child.ts 中

@Input() config: Function
...
retrieve() {
    const conf = this.config();
}

我收到错误“this.config 不是函数”

另外,我尝试使用 EventEmitter 但这一次,它返回“未定义”

在 parent.html 中

<child-component (config)="getConfig(data)"></child-component>

在 child.ts 中

@Output() config = new EventEmitter();
...
retrieve() {
    const conf = this.config.emit;
}

标签: angular

解决方案


注入ParentComponentChildComponent调用函数如下:

在你的ChildComponent.ts,

constructor(public parentComponent: ParentComponent) {}

在你的ChildComponent.html,

<child-component [config]="parentComponent.getConfig(data)"></child-component>

推荐阅读