0

I am trying to return a letter grade based on specified criteria using ngSwitch. What am I doing wrong? Sometimes it returns all 5 letter grades when I refresh the page.

A: 100-90 B: 89-80 C: 79-70 D: 69-60 F: < 60

This is my app.component.html file:

<h1>
  Your grade is a {{x}} percent.
</h1>

<div [ngSwitch]="true">
  <p *ngSwitchCase="x > 89">A</p>
  <p *ngSwitchCase="x > 79">B</p>
  <p *ngSwitchCase="x > 69">C</p>
  <p *ngSwitchCase="x > 59">D</p>
  <p *ngSwitchDefault>F</p>
</div>

This is my component.ts file: (this is assigning a random number using Math.random)

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'title';
  x: number;

  ngOnInit(){
    this.x = Math.floor(Math.random()*100 - 20 + 1) + 20;
  }
}
kaya3
  • 47,440
  • 4
  • 68
  • 97
libracorn
  • 317
  • 4
  • 9
  • 1
    Looks like your ngswitch is finding a condition where one or more statements are true. Example: x = 90 makes it so all meet the condition. Per their documentation "Every view that matches is rendered."... try adding an additional check to each expression to check for the low and high value to make only one true. Like x > 59 && x <= 69 – Alejandro Mar 10 '20 at 01:44
  • Hey @Alejandro, I am trying to make it so that the SwitchCase prompt a letter grade based on the random number that is generated. Is there a way to specify a range of numbers for the switch cases? For example a letter grade of an A would be the range of "90-100". – libracorn Mar 10 '20 at 01:47
  • @Alejandro Thank you so much Alejandro! That fixed it. May you add this solution to the answer the question section so I can mark it off as the correct answer? – libracorn Mar 10 '20 at 01:54
  • Sure, happy to help – Alejandro Mar 10 '20 at 01:57

2 Answers2

2

Looks like your ngswitch is finding a condition where one or more statements are true. Example: x = 90 makes it so all meet the condition. Per their documentation "Every view that matches is rendered."... try adding an additional check to each expression to check for the low and high value to make only one true. Like x > 59 && x <= 69

Alejandro
  • 413
  • 3
  • 9
0

Your switch cases need to have upper bounds:

<div [ngSwitch]="true">
    <p *ngSwitchCase="x > 89">A</p>
    <p *ngSwitchCase="x > 79 && x <= 89">B</p>
    <p *ngSwitchCase="x > 69 && x <= 79">C</p>
    <p *ngSwitchCase="x > 59 && x <= 69">D</p>
    <p *ngSwitchDefault>F</p>
</div>

Aside: This is not really the switch case's intended functionality, you could just as easily do this with *ngIf. Ideally, you'd want the variable you're evaluating in ngSwitch, and then all its possible values as cases.