【发布时间】:2020-03-10 01:37:17
【问题描述】:
我正在尝试使用 ngSwitch 根据指定标准返回字母等级。我究竟做错了什么?有时当我刷新页面时它会返回所有 5 个字母等级。
答:100-90 乙:89-80 C: 79-70 D:69-60 F:
这是我的 app.component.html 文件:
<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>
这是我的 component.ts 文件:(这是使用 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;
}
}
【问题讨论】:
-
看起来您的 ngswitch 正在寻找一个或多个陈述为真的条件。示例:x = 90 使得它都满足条件。根据他们的文档“每个匹配的视图都会被渲染。”...尝试为每个表达式添加一个额外的检查,以检查低值和高值以使只有一个为真。像 x > 59 && x
-
嘿@Alejandro,我正在尝试让 SwitchCase 根据生成的随机数提示字母等级。有没有办法为开关盒指定一个数字范围?例如,A 的字母等级将是“90-100”的范围。
-
@Alejandro 非常感谢亚历杭德罗!那解决了它。您能否将此解决方案添加到问题部分的答案中,以便我将其标记为正确答案?
-
好的,很乐意提供帮助
标签: javascript angular ng-switch