Angular2 - ngIf在ng

时间:2017-03-08 21:14:50

标签: angular ngfor ngif

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

例如,我想检查巧克力是黑色还是白色。根据这一点,我想显示正确的文字。

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

如何修复代码,以便它可以正常工作?

3 个答案:

答案 0 :(得分:8)

问题是您错过'(单引号)string后面black&amp; 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>

答案 1 :(得分:2)

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() { }
}

答案 2 :(得分:-1)

<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()