简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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