javascript - 将动态函数从父组件传递给孙组件Angular
问题描述
我正在为我的 Angular 应用程序创建一个公共表组件,以便该组件接受行、列的输入,以及一些操作按钮处理函数和渲染表。
我通过这种方式,可以使用单个组件来为整个应用程序呈现表格。
//parent-component.ts
parentFunction1(){
//edit User
}
parentFunction2(){
//delete User
}
parentFunction3(){
//view user
}
我从父组件传递数据为
//inside some-parent.component.html
<common-table
[columns]="columnConfig"
[dataSource]="rowConfig">
</common-table>
在我的common-table.component.html
中,根据条件,我需要将不同的组件渲染为:
//inside common-table.component.html
<table-cell [row]="row" [column]="column"></table-cell>
从table-cell.component.html
我需要调用parent-component.ts
. 对于不同的组件,我的函数名称可能会有所不同,是否有任何角度的方法,以便如果 json
[
{
name: 'Edit',
type: 'button',
outputHandler:parentFunction1
},
{
name: 'Delete',
type: 'button',
outputHandler:parentFunction2
},
{
name: 'View',
type: 'button',
outputHandler:parentFunction3
}
]
像这样可以从父组件传递并从孙子使用父组件的功能table-cell.component.html
我可以使用输出和事件发射器,但是由于传递的函数数量和函数名称可能会有所不同,所以它不能被硬连接。如何实现这一点。请帮忙,因为我搜索了很多但无法找到解决方案。
解决方案
这就是你的根组件的样子。
export class AppComponent {
title = "CodeSandbox";
myConfig: ConfigModel[] = [
{
name: "Edit",
type: "button",
outputHandler: this.parentFunction1
},
{
name: "Delete",
type: "button",
outputHandler: this.parentFunction2
},
{
name: "View",
type: "button",
outputHandler: this.parentFunction3
}
];
parentFunction1() {
console.log("parent func 1");
}
parentFunction2() {
console.log("parent func 2");
}
parentFunction3() {
console.log("parent func 3");
}
}
当您将此配置传递给您的大子组件时。您可以直接从配置对象调用该函数。
<div *ngFor="let item of config">
<button (click)="action(item)">{{item.name}}</button>
</div>
export class ActionComponent {
@Input() config: ConfigModel[];
action(item: ConfigModel) {
console.log(item);
item.outputHandler();
}
}
推荐阅读
- php - 按销售分类产品 - woocommerce
- angular - canDeactivate 不适用于 Angular 材质模态窗口
- geometry - 如何找到屋顶三角形的坐标?
- sql - 有没有办法在不执行 hive SQL 的情况下获取 hive SQL 返回的字段和类型
- java - 从 unix 值获取前一小时/前一天的时间戳
- java - 我收到一个字符串数组,并希望根据数组中收到的字符串访问哈希图
- hibernate - @OneToOne 关系中的两个问题
- ruby-on-rails - 如何识别瓶颈并优化慢速测试套件?
- javascript - 通知 mat-table 它应该扩展以适应 mat-cells?
- r - 如何使用for循环创建数据框?