繁体   English   中英

角度2:结合* ngIf和* ngFor使用最后一个未定义的项目执行循环

[英]angular 2: combining *ngIf and *ngFor executes loop with a last undefined item

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;
  }
}

正如在这个代码块中可以看到的那样,第二个* ngFor将被执行一次。

现在这是一个错误吗? 还是我只是禁止一起使用* ngFor和* ngIf? 我找不到与此有关的任何文档。

不支持同一元素上的*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>
 
  

你也可以用这个

<template let-v ngFor [ngForOf]="myValues">
        <div *ngIf="show">
          This is my value: {{v}}
        </div>
</template>

暂无
暂无

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

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