2017-03-08 178 views
2

我想檢查實際元素是否有值。Angular2 - ngIf in 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> 

如何修復代碼,使其工作?

回答

7

的問題是你錯過了'(單引號)後面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> 
-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()

+0

複製錯誤....但那不是我正在尋找的答案:) – ALSTRA

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

代碼窩rks here:https://plnkr.co/edit/eOwcs5?p=preview – nekkon

+0

如何在html代碼中綁定「模板」? – ALSTRA

+0

對不起,但我不明白你的問題,你能更具體嗎? – nekkon