[英]How to group angular components with a root component like how the App-Component works
[英]Angular create Selector Tag <app-component> using variable or loop
我需要使用變量制作app.component.html的選擇器標簽。
假設變量名是: componentVar:string
我需要我的app.component.html:
<componentVar></componentVar>
或<app-componentVar></app-componentVar>
您可以在ViewcontainerRef中動態創建組件,如下所示:
https://stackblitz.com/edit/angular-4asbmc
(不要忘記在app模塊的entryComponents中添加要在dom中動態注入的組件)
一旦您能夠插入組件,您就可以管理哪些組件必須插入您的條件。
編輯
您可以迭代一個看起來像這樣的組件數組:
let componentArray = [HeaderComponent, BannerComponent, FooterComponent];
然后遍歷此數組,調用在viewcontainer引用中插入組件的方法。
createComponent(component) {
const factory = this.factoryResolver.resolveComponentFactory(component);
const componentRef = factory.create(yourViewContainerRef.parentInjector);
yourViewContainerRef.insert(componentRef.hostView);
}
雖然從應用程序組件html模板中調用組件會更容易,但在模板中有類似的東西:
<app-header *ngIf="yourConditions..."></app-header>
<app-banner *ngIf="otherConditions..."></app-banner>
<!-- and so on.... -->
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.