如何使用变量动态调用组件或服务?

时间:2019-04-12 12:18:13

标签: javascript angular

在Angular中,有一种方法可以基于我收到的变量来调用组件?

例如:   如果我尝试使用一种方法来做到这一点,那么它会很好

  const function = 'myFunction';
  this.myComponent[function]();

程序将调用

   this.myComponent.myFunction();

是否可以对组件或服务执行相同的操作?      像这样:

    const function = 'myFunction';
    const component = 'myComponent';
    this[component][func]();

程序将调用:

   this.myComponent.myFunction();

我这样做是为了避免使用很多IF,因为我要调用或不调用10个以上的组件

2 个答案:

答案 0 :(得分:1)

您可以按照您所说的去做,这里是example

此外,这种IF和10个组件的模式看起来像是代码的味道。如果需要,可以在此处发布它,我们可以尝试为该问题找到更好的解决方案。

下次记住时,请先尝试,然后再提出问题。

答案 1 :(得分:0)

可以。在您的父组件模板中:

<div>
    <app-header></app-header>
    <app-home [state]='{id : row.id}' ></app-home>
</div>
<input type='button' (click)='click("g")' value="Call G"/><br />
<input type='button' (click)='click("f")' value="Call F"/><br />

在组件中:

@ViewChild(HomeComponent) home;

click(e){
  this.home[e]();
}

在子组件中:

  f(){
    console.log('function called')
  }

  g(){
    console.log('g called');
  }