angular - 在父级调用方法并从子级获取返回值
问题描述
我的目标是,从子组件中,我想在父组件中调用一个方法并获取返回值。我尝试了以下方法,但没有成功。
在 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;
}
解决方案
注入ParentComponent
并ChildComponent
调用函数如下:
在你的ChildComponent.ts
,
constructor(public parentComponent: ParentComponent) {}
在你的ChildComponent.html
,
<child-component [config]="parentComponent.getConfig(data)"></child-component>
推荐阅读
- oracle-sqldeveloper - oracle sql developer 19.2.1 在登录提示中不显示连接名称。有没有办法在这个版本中恢复它?
- sequelize.js - sequelize 迁移不读取 dotenv 变量
- java - 如何在 SonarQube 中只运行一个特定规则?
- asp.net-core - 自定义 CardDAV 服务器:客户端(尤其是 iOS)似乎不请求实际联系人
- java - XText 嵌入编辑器无法注入
- java - 如何在实体类中不写具体外键列的情况下使用外键变量?
- mysql - sql查询以获取具有条件的行
- ios - 在 mac os 上运行“CouchbaseLiteSwift”pod lib?
- reactjs - 如何添加水平滚动条以访问 Material-UI 表中的溢出列
- bash - 如何在主 shell 脚本结束时保持内部 shell 脚本运行?