page-bmi.component.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { Component, OnInit } from '@angular/core';
  2. import { Router } from '@angular/router';
  3. import { AlertController, IonButton, IonButtons, IonContent, IonHeader, IonIcon, IonInput, IonItem, IonLabel, IonTitle, IonToolbar } from '@ionic/angular/standalone';
  4. import { FormsModule } from '@angular/forms'; // 导入 FormsModule
  5. import { CommonModule } from '@angular/common'; // 导入 CommonModule
  6. import { chevronBackOutline } from 'ionicons/icons';
  7. import { addIcons } from 'ionicons';
  8. addIcons({chevronBackOutline});
  9. @Component({
  10. selector: 'app-page-bmi',
  11. templateUrl: './page-bmi.component.html',
  12. styleUrls: ['./page-bmi.component.scss'],
  13. standalone: true,
  14. imports:[IonHeader,IonToolbar,IonTitle,IonButton,IonButtons,IonContent,IonItem,IonLabel,IonInput,FormsModule,CommonModule,IonIcon]
  15. })
  16. export class PageBmiComponent implements OnInit {
  17. ngOnInit() {this.resetForm();} // 页面加载时清空数据
  18. height: number|null =null; // 身高
  19. weight: number|null =null; // 体重
  20. bmi: number|null=null; // BMI 值
  21. constructor(private router: Router,private alertController: AlertController) {this.resetForm();}
  22. // 计算 BMI
  23. async calculateBMI() {
  24. if (this.height !=null && this.weight !=null) {
  25. if(this.height >0 && this.weight >0) {
  26. const heightInMeters = this.height / 100; // 将身高转换为米
  27. this.bmi = this.weight / (heightInMeters * heightInMeters); // 计算 BMI
  28. } else {
  29. const alert = await this.alertController.create({
  30. header: '身高体重不能为0!',
  31. buttons: ['确定']
  32. });
  33. await alert.present(); // 显示弹出框
  34. }
  35. } else {
  36. const alert = await this.alertController.create({
  37. header: '身高体重不能为空!',
  38. buttons: ['确定']
  39. });
  40. await alert.present(); // 显示弹出框
  41. }
  42. }
  43. //清空数据
  44. // 清空输入数据
  45. resetForm() {
  46. this.height = null;
  47. this.weight = null;
  48. this.bmi = null;
  49. }
  50. // 返回上一个页面
  51. goBack() {
  52. this.router.navigate(['/tabs/tab3'], { replaceUrl: true }); // 使用 replaceUrl 强制重载页面
  53. }
  54. }