簡體   English   中英

是否可以使用ngFor顯示多個組件選擇器標簽?

[英]Is it possible to use ngFor to display multiple component selector tags?

我在angular 2中有一個問題。因此,我可以使用ngFor從本地json顯示{{data}}標簽並顯示數據。

但是我想知道是否有一種方法可以呈現存儲在json中的組件選擇器標簽並在ng for中顯示它們。 例如,我的文件中包含以下json component.ts :(有關該問題的說明,請參閱評論)

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>

有什么建議可能有更好的方法嗎?

您不能離開選擇器。 無論如何,這在Ahead of Time(AoT)編譯器的生產中都行不通,因為編譯器在構建時運行,並且正是將選擇器與組件和指令相匹配的原因。

如果您只考慮有限的標記集,則可以使用ngSwitch 您支持的每個組件都是switch case ,您可以選擇通過JSON中的某些字符串屬性顯示哪個組件。 整個[ngSwitch]將是ngFor項目。

如果需要支持更復雜的場景,並且您正在使用Angular 4,則可以使用ngComponentOutlet' 這仍然需要類型(導入類)而不是選擇器。

最后,也是Angular 4,對於通常動態加載組件,您可以通過此庫https://github.com/apoterenko/ngx-dynamic-template支持的多種方式選擇最適合您的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM