【问题标题】:Is it possible to use ngFor to display multiple component selector tags?是否可以使用 ngFor 显示多个组件选择器标签?
【发布时间】:2017-07-09 00:31:29
【问题描述】:

我有一个关于角度 2 的问题。 所以我可以使用 ngFor 从本地 json 显示 {{data}} 标签并显示数据。

但是我想知道是否有一种方法可以渲染存储在 json 中的组件选择器标签并将它们显示在 ng for 中。例如, 我的文件中有这个 json component.ts:(有关该问题的说明,请参阅 cmets)

import { Component, OnInit } from '@angular/core';
import * as jQuery from 'jquery';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
widgets;
  constructor() { }

  ngOnInit() {

    this.widgets = [
{
  "widgetcode": "<app-analytics-widget></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-club-chooser></app-club-chooser>" //Existing component selector tag within the angular cli system
},
{
  "widgetcode": "<app-account-widget></app-account-widget>" //Existing component selector tag within the angular cli system
}



    ]
  }

}

我的 component.html 文件:

    <div class="DahsboardWrapper">

<!-- DashBoard Ges here -->

<!-- widget elements go here -->
<div class="DashoardHeaderClass" id="dashboard">
Dashboard Loaded
<div class="WidgetAreaWrapper">
<div class="widgets" *ngFor="let widget of widgets">


 <!-- {{widget.widgetcode}}  Not working atm..-->
<!-- this is displayng just plain text -->
</div>

<!-- This is working --> 
<app-analytics-widget></app-analytics-widget>
<app-club-chooser></app-club-chooser>
<app-account-widget></app-account-widget>

</div>
</div>

有什么建议可能有更好的方法吗?

【问题讨论】:

    标签: javascript jquery html angular angular-cli


    【解决方案1】:

    你不能离开选择器。无论如何,这在使用 Ahead of Time (AoT) 编译器的生产环境中是行不通的,因为编译器在构建时运行,它将选择器与组件和指令相匹配。

    如果您的标签集有限,您可以使用ngSwitch。您支持的每个组件都是switchcases 之一,您可以通过 JSON 中的某个字符串属性选择要显示的组件。整个 [ngSwitch] 将是 ngFor 项。

    如果您需要支持更复杂的场景,并且您使用的是 Angular 4,您可以使用ngComponentOutlet'。这仍然需要类型(导入类)而不是选择器。

    最后,还有 Angular 4,对于一般动态加载组件,您可以通过此库 https://github.com/apoterenko/ngx-dynamic-template 中支持的多种方式来选择对您最有意义的方式。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-19
    • 2011-06-27
    • 1970-01-01
    • 2021-12-27
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多