ALSTRA
ALSTRA

Reputation: 661

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?

Upvotes: 3

Views: 5299

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

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>

Upvotes: 9

nekkon
nekkon

Reputation: 107

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

Upvotes: 2

Antoine Clavijo
Antoine Clavijo

Reputation: 1305

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

Upvotes: -1

Related Questions