计算输入时的Angular ExpressionChanged错误

时间:2019-01-06 01:31:56

标签: angular

我有一个表格,该表格接受用户选择的值并输出计算出的值。当用户输入数据时,数字会更新。当第一个数字放入时,它计算Number(5) Number((float) 12.5) operator=(const Number&) ~Number() Number(8) operator=(const Number&) ~Number() ~Number() ,但是x + y是当前零,返回y。但是,当用户输入x+0值时,它将返回错误:

y

我正在使用ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'value: 215'. Current value: 'value: 163.4'.,但我也在用于数学的函数中尝试过ngOnInitAfterViewInitAfterContentInit,并尝试过使用{{1} },但似乎无法解决问题。

Stackblitz:https://stackblitz.com/edit/angular-bupkrr

添加体重,然后添加身体脂肪百分比,您会在控制台中注意到错误。

2 个答案:

答案 0 :(得分:0)

仅更改下面的TS文件...请检查

import { Component, OnInit } from '@angular/core';
import {ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'phyto-calc';
  leanBodyMassValue = 0;
  bodyFatValue = 0;
  goalWeightValue = 0;

  constructor(private cdref: ChangeDetectorRef) {}

  ngOnInit() {}
  ngAfterContentChecked() {
    this.leanBodyMassValue = this.leanBodyMassValue;
    this.cdref.detectChanges();
  }

  pctRange(low, high) {
    const x = new Array();
    for (let y = low; y <= high; y++) {
      x.push(y);
    }
    return x;
  }

  leatBodyMass(cw: number = 0, bf: number = 0) {
    this.leanBodyMassValue = cw - bf;
    return this.leanBodyMassValue;
  }

  bodyFatCalc(cw: number = 0, cbf: number = 0) {
    this.bodyFatValue = cw * (cbf / 100);
    return this.bodyFatValue;
  }

  goalWeight(gbf: number = 0, lbmv: number = 0) {
    this.goalWeightValue = gbf * (lbmv / 100);
    return this.goalWeightValue;
  }
}

答案 1 :(得分:0)

仅当bodyFatValue更改时,您才能计算bodyFat Percent

https://stackblitz.com/edit/angular-949enz?file=src%2Fapp%2Fapp.component.html

这是我的改变

app.component.html

 <mat-select [(value)]="cbf" ... >
   ...
 </mat-select>

 <mat-select (selectionChange)="changeBodyfat($event,cw)" ... >
   ...
 </mat-select>

<input
  [value]="bodyFatCalc(cw, cbf)"
  name="bodyfatlbs"
  ...
/>

<input
  [value]="bodyFatValue"
  name="bodyfatlbs"
  ...
/>

app.component.ts

  bodyFatCalc(cw: number = 0, cbf: number = 0) {
    this.bodyFatValue = cw * (cbf / 100);
    return this.bodyFatValue;
  }

  changeBodyfat(selected, cw) {
    const cbf = selected.value;
     this.bodyFatValue  = this.bodyFatCalc(cw , cbf);
  }

  bodyFatCalc(cw: number = 0, cbf: number = 0) {
    return cw * (cbf / 100);
  }