点击后从输入中获取值并计算它 - Angular 5

时间:2018-04-13 13:59:16

标签: javascript angular typescript

我想编写一个函数,从两个输入中获取两个值,并计算像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; ? 感谢帮助!

2 个答案:

答案 0 :(得分:0)

weightgrowth属性上使用双向数据绑定,只需将它们作为参数传递给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)
}

Demo

然后修改您的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);
  }
}

Live demo