Issue
I am using a value called count
which is initially set to zero. I have created two buttons to increment and decrement the count value.
<button (click)="increment()">++</button>
<h3 class="count">{{ count }}</h3>
<button (click)="decrement()">--</button>
I want to create another div
which displays the count value separately with different colors according the switch conditions.
<div [ngSwitch]="count">
<h1 style="color: red" *ngSwitchCase="count % 2 == 0">{{ count }}</h1>
<h1 style="color: green" *ngSwitchCase="count % 3 === 0">{{ count }}</h1>
<h1 style="color: blue" *ngSwitchCase="count % 7 === 0">{{ count }}</h1>
<h1 *ngSwitchDefault>{{ count }}</h1>
</div>
The count value is displayed but the color remains black. Can anyone tell me what I am doing wrong? I am new to angular.
Solution
the ngSwitchCase is working as expected. imagine this case:
switch (this.count) {
case (this.count % 2 === 0) as any:
break;
case (this.count % 3 === 0) as any:
break;
case (this.count % 3 === 0) as any:
break;
default:
break;
}
you would always land in the default
case because you are doing a switch on count, and the cases are either true
or false
why you don't use *ngIf
?
or another solution to your problem cold be this:
<div [ngSwitch]="count">
<h1 style="color: red"
*ngSwitchCase="count % 2 === 0 ? count : false">{{ count }}</h1>
<h1 style="color: green"
*ngSwitchCase="count % 3 === 0 ? count : false">{{ count }}</h1>
<h1 style="color: blue"
*ngSwitchCase="count % 7 === 0 ? count : false">{{ count }}</h1>
<h1 *ngSwitchDefault>{{ count }}</h1>
</div>
Answered By - Zerotwelve
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.