简体   繁体   English

Angular2 - 在ngFor中的ngIf

[英]Angular2 - ngIf in a ngFor

I want to check if the actual element has a value or not. 我想检查实际元素是否有值。

For Example I want to check if the chocolate is black or white. 例如,我想检查巧克力是黑色还是白色。 Depending on this, I want to display the right text. 根据这个,我想显示正确的文本。

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

How to fix the code, so that it works? 如何修复代码,以便它可以工作?

The problem is you missed ' (single quote) behind string which is black & white 问题是你错过了' (单引号)后面stringblackwhite

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

modify chocolate .getName() to chocolate.getName() chocolate .getName()修改为chocolate.getName()

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

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