我想编写一个函数,从两个输入中获取两个值,并计算像BMI(Body Mass Index)之类的东西。 我的HTML文件:
<div class="input-group mb-3 weight-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Weight</span>
</div>
<input ng-model="weight" type="text" class="form-control" placeholder="[kg]" aria-label="Waga[kg]" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3 growth-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Growth</span>
</div>
<input ng-model="growth" type="text" class="form-control" placeholder="[m]" aria-label="Wzrost[m]" aria-describedby="basic-addon1">
</div>
<button (click)="calculate()" type="button" class="btn btn-primary btn-sm ml-3">Large button</button>
<div class="alert alert-dark" id="result" role="alert">
</div>
我的TS档案:
import { Component, OnInit } from '@angular/core';
import { NgModel } from '@angular/forms';
@Component({
selector: 'app-inputs',
templateUrl: './inputs.component.html',
styleUrls: ['./inputs.component.css'],
})
export class InputsComponent implements OnInit {
constructor() { }
ngOnInit() {
}
calculate() {
}
}
我应该在函数calculate()中编写什么来查看从权重和增长输入中获取的值,以及如何将变量bmi中的值导出到div id =&#34;结果&#34; ? 感谢帮助!
答案 0 :(得分:0)
在weight
和growth
属性上使用双向数据绑定,只需将它们作为参数传递给calculate
函数。
<div class="input-group mb-3 weight-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Weight</span>
</div>
<input [(ngModel)]="weight" type="text" class="form-control" placeholder="[kg]" aria-label="Waga[kg]" aria-describedby="basic-addon1">
</div>
<div class="input-group mb-3 growth-div col-6">
<div class="input-group-prepend">
<span class="input-group-text">Growth</span>
</div>
<input [(ngModel)]="growth" type="text" class="form-control" placeholder="[m]" aria-label="Wzrost[m]" aria-describedby="basic-addon1">
</div>
<button (click)="calculate(weight, growth)" type="button" class="btn btn-primary btn-sm ml-3">Large button</button>
<div class="alert alert-dark" id="result" role="alert">
</div>
和
calculate(weight, growth) {
console.log(weight, growth)
}
然后修改您的calculate
函数以实际执行有用的操作。
答案 1 :(得分:0)
利用Angular与[(ngModel)]
的双向数据绑定。这样你甚至不需要计算功能,并且可以实时获得计算预览。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template:`
<input [(ngModel)]="mass" placeholder="mass" />
<input [(ngModel)]="height" placeholder="height" />
<div *ngIf="mass && height"> {{ bmi }} </div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
mass = 0;
height = 0;
get bmi() {
return this.mass / Math.pow(this.height, 2);
}
}