http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div class="container">
<div *ngFor="let v of myValues;">
This is my value: {{v}}
</div>
<hr>
<div *ngIf="show" *ngFor="let v of myValues;">
This is my value: {{v}}
</div>
`,
})
export class AppComponent {
public user: User = {
name: 'John',
address: {
address1: '11, High Street',
postcode: '1234'
}
}
myValues = ['one','two','three'];
show = true;
public save(form: IUser, isValid: boolean) {
console.log(form, isValid);
}
}
export interface User {
name: string;
address?: {
address1?: string;
postcode?: string;
}
}
从这个plunkr中可以看出,第二个* ngFor将被执行太多次。
现在这是一个错误吗?或者我是否被禁止同时使用* ngFor和* ngIf?我找不到任何关于此的文件。
答案 0 :(得分:4)
*ngIf
和*ngFor
作为解决方法,您可以使用:
更新(2.0.0)
<ng-container *ngIf="show">
<div *ngFor="let v of myValues;">
This is my value: {{v}}
</div>
</ng-container>
<强>原始强>
<击> 撞击>
<击> <template [ngIf]="show">
<div *ngFor="let v of myValues;">
This is my value: {{v}}
</div>
</template>
击> <击> 撞击>
答案 1 :(得分:2)
您也可以使用此
<template let-v ngFor [ngForOf]="myValues">
<div *ngIf="show">
This is my value: {{v}}
</div>
</template>