我正在为我的 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
的函数。对于不同的组件,我的函数名称可能会有所不同,有什么方法可以在angular中使用,如果json
[
{
name: 'Edit',
type: 'button',
outputHandler:parentFunction1
},
{
name: 'Delete',
type: 'button',
outputHandler:parentFunction2
},
{
name: 'View',
type: 'button',
outputHandler:parentFunction3
}
]
像这样可以从父组件传递并使用孙子组件的父组件的功能table-cell.component.html
我可以使用输出和事件发射器,但由于传递的函数数量和函数名称可能会有所不同,因此不能硬编码。如何实现这一目标。请帮助,因为我搜索了很多但找不到解决方案。
答案 0 :(得分:1)
这就是你的根组件的样子。
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();
}
}