【问题标题】:conditional importing of child components into parent's template angular 5有条件地将子组件导入到父模板 angular 5
【发布时间】:2018-07-23 19:53:18
【问题描述】:

我有一个父组件和大约 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>

有什么建议吗?

【问题讨论】:

    标签: angular angular5 angular-components


    【解决方案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(不要忘记在模块中导入组件)。

    无法使用数据来呈现不同的组件 (&lt;widget.action&gt;&lt;/widget.action&gt;)。

    【讨论】:

    • 正如我所说我有 60 个子组件,这是应用 switch 案例的有效方法吗?
    • 是的,您选择哪种方法并不重要,您总是需要 60 个表达式(例如 widget.action === 'color')。
    • 其实我在想组件的动态加载,一些获取组件名称的函数,加载它并将它放在适当的位置。
    猜你喜欢
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2018-12-11
    • 2017-11-14
    • 2020-09-03
    • 2018-09-12
    相关资源
    最近更新 更多