2017-03-08 78 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