Angular 2 个条件 ngFor
Angular 2 conditional ngFor
我正在尝试清理我的模板代码。我有以下内容:
<ul>
<li *ngIf="condition" *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
<li *ngIf="!condition" *ngFor="let b of array2">
<p>{{b.firstname}}</p>
<p>{{b.lastname}}</p>
</li>
</ul>
有没有办法有条件地选择 array1
或 array2
来循环使用 *ngIf
或其他东西,这样我就不必重复这么多模板代码?这只是一个例子;我的实际 <li>
包含更多内容,所以我真的不想重复自己。谢谢!
<li *ngFor="let a of (condition ? array1 : array2)">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
在 ngFor 循环外使用带有 [ngIf] 的模板标签。
<ul>
<template [ngIf]="condition">
<li *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
</template>
<template [ngIf]="!condition">
<li *ngFor="let b of array2">
<p>{{b.firstname}}</p>
<p>{{b.lastname}}</p>
</li>
</template>
</ul>
另请阅读此处的模板语法:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template
您不能在同一元素中同时拥有 *ngFor
和 *ngIf
。您可以使用 *ngFor
在 <li>
中创建一个元素。喜欢:
<li *ngIf="condition">
<ul>
<li *ngFor="let a of array1">
或者使用*ngFor
里面的条件。像这样:
<li *ngFor="let a of (condition?array1:array2)">
或者您可以使用 指示的模板。
您可以使用 ng-container
,DOM 无法识别,因此仅用于条件。请参阅下面的示例:
<tr *ngFor="let company of companies">
<ng-container *ngIf="company.tradingRegion == 1">
<td>{{ company.name }}</td>
<td>{{ company.mseCode }}</td>
</ng-container>
</tr>
上面的代码将:`
Display a list of all companies where the tradingRegion == 1
`
我们可以根据条件使用 bootstrap 显示 属性 隐藏元素。
<li [ngClass]="{'d-none': condition}" *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
我正在尝试清理我的模板代码。我有以下内容:
<ul>
<li *ngIf="condition" *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
<li *ngIf="!condition" *ngFor="let b of array2">
<p>{{b.firstname}}</p>
<p>{{b.lastname}}</p>
</li>
</ul>
有没有办法有条件地选择 array1
或 array2
来循环使用 *ngIf
或其他东西,这样我就不必重复这么多模板代码?这只是一个例子;我的实际 <li>
包含更多内容,所以我真的不想重复自己。谢谢!
<li *ngFor="let a of (condition ? array1 : array2)">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
在 ngFor 循环外使用带有 [ngIf] 的模板标签。
<ul>
<template [ngIf]="condition">
<li *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>
</template>
<template [ngIf]="!condition">
<li *ngFor="let b of array2">
<p>{{b.firstname}}</p>
<p>{{b.lastname}}</p>
</li>
</template>
</ul>
另请阅读此处的模板语法:https://angular.io/docs/ts/latest/guide/template-syntax.html#!#star-template
您不能在同一元素中同时拥有 *ngFor
和 *ngIf
。您可以使用 *ngFor
在 <li>
中创建一个元素。喜欢:
<li *ngIf="condition">
<ul>
<li *ngFor="let a of array1">
或者使用*ngFor
里面的条件。像这样:
<li *ngFor="let a of (condition?array1:array2)">
或者您可以使用
您可以使用 ng-container
,DOM 无法识别,因此仅用于条件。请参阅下面的示例:
<tr *ngFor="let company of companies">
<ng-container *ngIf="company.tradingRegion == 1">
<td>{{ company.name }}</td>
<td>{{ company.mseCode }}</td>
</ng-container>
</tr>
上面的代码将:`
Display a list of all companies where the tradingRegion == 1
`
我们可以根据条件使用 bootstrap 显示 属性 隐藏元素。
<li [ngClass]="{'d-none': condition}" *ngFor="let a of array1">
<p>{{a.firstname}}</p>
<p>{{a.lastname}}</p>
</li>