Angular2 - ngFor 中的 ngIf

Angular2 - ngIf in a ngFor

我想检查实际元素是否有值。

例如,我想检查巧克力是黑巧克力还是白巧克力。据此,我想显示正确的文本。

<ng-container *ngFor="let chocolate of product.getChocolates();">
     <md-card *ngIf="chocolate.getName() == black">IT IS BLACK</md-card>
     <md-card *ngIf="chocolate.getName() == white">IT IS WHITE</md-card>
</ng-container>

如何修复代码,使其正常工作?

<ng-container *ngFor="let chocolate of product.getChocolates();">
     <md-card *ngIf="chocolate.getName() == black">IT IS BLACK</md-card>
     <md-card *ngIf="chocolate.getName() == white">IT IS WHITE</md-card>
</ng-container>

修改chocolate .getName()chocolate.getName()

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<div *ngFor="let chocolate of chocolates">
     <div *ngIf="chocolate.name == 'black'">IT IS BLACK</div>
     <div *ngIf="chocolate.name == 'white'">IT IS WHITE</div>
</div>`
})
export class AppComponent{
  chocolates:any=[{
    name:'black'
  },
  {
    name:'white'
  }];

  constructor() { }
}

问题是你错过了 string 后面的 '(单引号),即 black & white

<ng-container *ngFor="let chocolate of product.getChocolates();">
     <md-card *ngIf="chocolate.getName() == 'black'">IT IS BLACK</md-card>
     <md-card *ngIf="chocolate.getName() == 'white'">IT IS WHITE</md-card>
</ng-container>