Home > Back-end >  Angular ngSwitchCase not working as expected
Angular ngSwitchCase not working as expected

Time:04-14

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 >{{ 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.

CodePudding user response:

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>

CodePudding user response:

A hack for that, would be something like this:

<div [ngSwitch]="true">
  <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>

But I am sure that we can think of better solutions:

For example, if the count is input, you can calculate the header color like that:

feature.component.ts

@Input() count!: number;

color = '';

ngOnChanges({count}: SimpleChanges) {
  if (count) {
    this.setColor();
  }
}

private setColor() {
  if (this.count % 2 === 0) {
    this.color = 'red';
  }
  ...
  ...
}

Then in the template would be like that:

<div> <h1 style="color: {{ color }}">{{ count }}</h1> </div>
  • Related