2016-11-15 52 views
0

我想在这样的代码来实现ngSwitch ngSwitch默认情况下:不执行

<div [ngSwitch]="accessLevel"> 
    <div class="customer" *ngSwitchCase="ENABLED"> 
     This is customer data 
    </div> 
    <div *ngSwitchDefault> 
     this is default 
    </div> 
    <div class="customer-blurr" *ngSwitchCase="DISABLED"> 
     This is disabled Customer Data 
    </div> 
</div> 

在我的情况accessLevel是不确定的,我期待this is default,但它显示:

This is customer data. 

This is disabled Customer Data. 

由于我从the official docs读取,如果没有匹配,它应该去默认情况下。我错过了什么吗?

回答

2

注意,*ngSwitchCase指令的值必须是表达匹配,而不是价值。在你的情况,你可能想比较字符串'ENABLED',而不是使用该名称的一些领域,因此它应该是如:

<div class="customer" *ngSwitchCase="'ENABLED'"> 
           <!--^note quotes --> 

你看到两个ENABLEDDISABLED案件因为那些都名字被定义,所以你实际上匹配undefined == undefined,评估truthy。因此默认值不显示,但均为的其他情况。

或者,您可以定义一些常量或枚举来进行比较,而不是传递字符串,这会改善代码的语义。

+0

非常好。谢谢 – Roxy

1

如下更改HTML:

<div [ngSwitch]="accessLevel"> 
    <div class="customer" *ngSwitchCase="'ENABLED'"> 
     This is customer data 
    </div> 
    <div *ngSwitchDefault> 
     this is default 
    </div> 
    <div class="customer-blurr" *ngSwitchCase="'DISABLED'"> 
     This is disabled Customer Data 
    </div> 
</div> 
+0

请注意,解释*为什么应该进行更改通常很有帮助。 – jonrsharpe

+0

好的,我从现在开始照顾它。 – ranakrunal9

+0

感谢您的回答,+1为您付出的努力。 – Roxy