【问题标题】:Passing dynamic functions from parent component to grandchild component Angular将动态函数从父组件传递给孙组件Angular
【发布时间】:2021-04-12 20:19:42
【问题描述】:

我正在为我的 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的父组件的功能

我可以使用输出和事件发射器,但是由于传递的函数数量和函数名称可能会有所不同,所以它不能硬连接。如何实现这一点。请帮忙,因为我搜索了很多但找不到解决方案。

【问题讨论】:

  • 您是否打算在组件配置中将函数名称作为字符串传递?
  • @VimalPatel 不,我不想将函数名作为字符串传递,我想传递整个函数
  • 这意味着作为函数引用。对吗?
  • 是的,我还希望如果我从大组件调用该函数,它可以像事件发射器一样访问父组件的属性
  • 为什么要从子组件访问父组件属性?我想你需要先检查你的组件设计。您正在偏离基本的组件交互。

标签: javascript angular events angular-material


【解决方案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();
  }
}

Working Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    相关资源
    最近更新 更多