【问题标题】:Angular 7 Dynamic variable name for imported component导入组件的Angular 7动态变量名称
【发布时间】:2020-03-18 06:15:12
【问题描述】:

在一个简单的 Angular 应用程序中,我创建了一个如下所示的测试组件:

test.component.ts

    import { Component } from '@angular/core';

    @Component({
      selector: 'test',
      template: `<h1>I am a test</h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class TestComponent  {

    }

我像这样在我的应用程序模块中导入:

app.component.ts

    import { Component } from '@angular/core';
    import { TestComponent } from './test.component';

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
      public TestComponent = TestComponent;
      dynamic = "Test";

      constructor(){
        console.log(TestComponent);
        console.log(this.TestComponent);
        console.log(this['TestComponent']);
        console.log(this[this.dynamic + 'Component']);
      }
    }

从这个主题Angular 5 Dynamic variable name 获得帮助,我能够动态获取我的组件名称(在实际示例中,动态变量会根据 API 调用响应而变化)。

我的问题是是否有任何方法可以实现相同的结果而不必将组件作为局部类变量传递,从而避免这一行

public TestComponent = TestComponent;

如果没有 this 关键字,动态变量不起作用,它会给我一个错误

console.log([this.dynamic + 'Component']);

我尝试在 stackblitz 中添加代码,但似乎无法共享它 (https://github.com/stackblitz/core/issues/215),但是将这两个文件复制到一个新的空 stackbitz (https://stackblitz.com/edit/angular-f4ars5) 以进行复制非常简单。

提前致谢。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    首先你需要了解下面这行

    this['TestComponent']
    

    在 javascript 中,您可以通过两种方式访问​​类属性。 Class.propertyClass["property"]。所以当你写this["TestProperty"]时,你实际上是在说,获取AppComponentInstance.TestProperty

    所以console.log([this.dynamic + 'Component']); 就像写.TextComponent 左边什么都没有。

    现在基于此,您到底想实现什么?获取类型或类型的实例?你想用这个类型做什么?

    您可以做的是在某个地方声明另一个全局类并在其中包含这些属性。检查this one for global variable declaration

    你的 json 可能是这样的:

    export class ComponentMapping
    {
        private TestComponent = TestComponent;
    }
    

    然后在你的类中相应地访问测试组件。

    【讨论】:

    • 感谢您解释第一部分。我的目标是动态添加所需的组件,这取决于 API 调用的响应。我有两个组件,我们称它们为"Component1""Component2",所以我的API 调用返回type = 1,然后我想使用该类型来动态获取组件的名称"Component" + type。所以我觉得 const 的全局变量解决方案不适用。
    • 为此,请尝试使用指令和组件工厂的官方方式angular.io/guide/dynamic-component-loader。让我知道这是否适合您。这个解决方案有一个声明的组件类型数组,根据一个值选择,在你的情况下是后端。
    • 这正是我所遵循的,然后直觉卡住了参数,我会再试一次,如果它成功了,我会告诉你。再次感谢。
    • 我终于使用了一个新服务(如示例),它返回一个具有键值对的对象,键代表从我的 API 返回的类型 (1, 2..)。再次感谢您的 cmets,引导我走向正确的方向。 :)
    • 干杯!很高兴我能帮上忙!
    猜你喜欢
    • 2019-08-05
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    相关资源
    最近更新 更多