将子组件有条件地导入父模板的角度5

时间:2018-02-13 12:30:53

标签: angular angular5 angular-components

我有一个父组件和类似60个子组件。根据父数据,我应该在* ngFor循环中加载适当的组件。这是我的代码:

<ng-container *ngFor="let widget of ribonData.widgets">
        <div *ngIf="some conditions"></div>

** here i should generate child components tag based on "widget.action" property. **
for example if "widget.action" is "color" i should generate <color-component></color-component>

      </ng-container>

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

利用Angular的NgSwitch Directive。像这样:

<ng-container *ngFor="let widget of ribonData.widgets">
    <div [ngSwitch]="widget.action">
        <div *ngSwitchCase="'color'">
            <color-component></color-component>
        </div>
        <div *ngSwitchDefault>
            <some-other-component></some-other-component>
        </div>
    </div>
</ng-container>

只需为每种类型的widget.action / component复制*ngSwitchCase(不要忘记导入模块中的组件)。

无法使用数据显示不同的组件(<widget.action></widget.action>)。