Angular 5点击获取输入值并实现BMI计算的技术问询
没问题,我来帮你搞定Angular 5里的BMI计算功能!先把你的HTML补全,再写对应的组件逻辑,一步步来:
1. 补全并修正HTML代码
你原来的代码里身高输入框没写完,而且Angular 5要用[(ngModel)](不是AngularJS的ng-model)来实现双向数据绑定,另外加上计算按钮和结果展示区域:
<div class="container mt-4"> <div class="input-group mb-3 weight-div col-6"> <div class="input-group-prepend"> <span class="input-group-text">Weight (kg)</span> </div> <input [(ngModel)]="weight" type="number" class="form-control" placeholder="Enter weight" aria-label="Weight"> </div> <div class="input-group mb-3 growth-div col-6"> <div class="input-group-prepend"> <span class="input-group-text">Height (m)</span> </div> <input [(ngModel)]="height" type="number" step="0.01" class="form-control" placeholder="Enter height" aria-label="Height"> </div> <button class="btn btn-primary" (click)="calculateBMI()">Calculate BMI</button> <div class="mt-3" *ngIf="bmiResult !== null"> <h4>Your BMI: <strong>{{ bmiResult | number:'1.2-2' }}</strong></h4> <p>{{ getBMICategory() }}</p> </div> </div>
这里把输入类型改成number,身高加了step="0.01"方便输入小数,还加了结果展示区域,用*ngIf控制显示,管道number:'1.2-2'让结果保留两位小数。
2. 编写组件TypeScript代码
在你的组件.ts文件里(比如bmi-calculator.component.ts),定义变量和计算函数,还要加输入验证避免错误:
import { Component } from '@angular/core'; @Component({ selector: 'app-bmi-calculator', templateUrl: './bmi-calculator.component.html', styleUrls: ['./bmi-calculator.component.css'] }) export class BmiCalculatorComponent { weight: number | null = null; height: number | null = null; bmiResult: number | null = null; calculateBMI(): void { // 先做输入验证:确保体重和身高都是正数 if (this.weight && this.height && this.weight > 0 && this.height > 0) { // BMI公式:体重(kg) / (身高(m)的平方) this.bmiResult = this.weight / (this.height * this.height); } else { alert('Please enter valid positive numbers for weight and height!'); this.bmiResult = null; } } getBMICategory(): string { if (!this.bmiResult) return ''; if (this.bmiResult < 18.5) { return 'Underweight'; } else if (this.bmiResult >= 18.5 && this.bmiResult < 25) { return 'Normal weight'; } else if (this.bmiResult >= 25 && this.bmiResult < 30) { return 'Overweight'; } else { return 'Obese'; } } }
3. 关键:导入FormsModule
因为用了[(ngModel)],必须在你的模块文件(比如app.module.ts)里导入FormsModule,否则双向绑定会失效:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; // 导入这个 import { AppComponent } from './app.component'; import { BmiCalculatorComponent } from './bmi-calculator/bmi-calculator.component'; @NgModule({ declarations: [ AppComponent, BmiCalculatorComponent ], imports: [ BrowserModule, FormsModule // 添加到imports数组里 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
这样整个功能就跑通了:输入体重和身高,点击按钮就能算出BMI,还会显示对应的体重类别,输入无效值的时候会弹出提示。
要是你想调整细节,比如结果精度、样式或者验证方式,随时说哈!
内容的提问来源于stack exchange,提问作者David J.
相关产品推荐
相关产品推荐

