简体   繁体   English

使用* ngFor渲染Angular html标签

[英]Using *ngFor rendering Angular html tags

I wanted to know if there is a way to use ngFor for rendering components, like in the codes in this link 我想知道是否有一种方法可以使用ngFor渲染组件,例如此链接中的代码

summarizing, I wanted to do something like this 总结一下,我想做这样的事情

<div *ngFor="let item of tabs" class="tab-content" id="myTabContent">
  <div
    class="tab-pane fade show active"
    [id]="item.tab"
    role="tabpanel"
    aria-labelledby="{{ item.tab }}-tab"
  >
    <app-{{item.tab}}></app-{{item.tab}}>
  </div>
</div>

assuming I have the components created and the tabs variable as such: 假设我已经创建了组件,并且tabs变量是这样的:

 tabs = [
        { title: "Impresoras", tab: "printers" },
        { title: "Mapa de Ataques", tab: "attacks" },
        { title: "Alerta de Vuelos", tab: "flights" }
    ];

Assuming (based on your code sample) that you have custom components for each tab (eg <app-printers> , <app-attacks> , <app-flights> ), you could use an *ngSwitch structural directive to accomplish your goal: 假设(基于代码示例)您为每个选项卡具有自定义组件(例如<app-printers><app-attacks><app-flights> ),则可以使用*ngSwitch结构指令来实现您的目标:

 <div *ngFor="let item of tabs" class="tab-content" id="myTabContent" [ngSwitch]="item.tab"> <div class="tab-pane fade show active" [id]="item.tab" role="tabpanel" aria-labelledby="{{ item.tab }}-tab" > <app-printers *ngSwitchCase="printers"></app-printers> <app-attacks *ngSwitchCase="attacks"></app-attacks> <app-flights *ngSwitchCase="flights"></app-flights> </div> </div> 

Certainly, you could also do this using *ngIf : 当然,您也可以使用*ngIf执行此操作:

 <div *ngFor="let item of tabs" class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" [id]="item.tab" role="tabpanel" aria-labelledby="{{ item.tab }}-tab" > <app-printers *ngIf="item.tab === 'printers'"></app-printers> <app-attacks *ngIf=item.tab === 'attacks'"></app-attacks> <app-flights *ngIf="item.tab === 'flights'"></app-flights> </div> </div> 

Hope that helps! 希望有帮助!

The ngFor statment is correct but the problem here is the tag, ngFor语句正确,但是这里的问题是标签,

<app-{{item.tab}}></app-{{item.tab}}>

app item tap could be a generic component with an Input decorator like: 应用程序项tap可能是具有Input装饰器的通用组件,例如:

<app-generic-tap [itemTap]="item.tap"><app-generic-tap>

Take a look to the Angular documentation especially in the @Input and @Output Decorators. 看一下Angular文档,尤其是@Input和@Output Decorators中的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM