计算FormGroup字段时,超出了最大调用堆栈大小

时间:2018-08-31 14:05:03

标签: angular typescript

我正在尝试创建一个带有angular / typescript的表单,其中将根据另一个字段中的数字自动计算字段。因此,例如,我们有Areasize_divided应该是字段Areasize的值,但应除以100。而Areasize是Areasize_divided乘以100的值

当前我遇到以下错误

  

错误RangeError:超出了最大调用堆栈大小

这是我的表单组:

formGroup = new FormGroup({
        Buildyear:           new FormControl(this.buildyear, [Validators.minLength(4), Validators.maxLength(4)]),
        Areasize:            new FormControl(this.areasize, [Validators.required] ),
        Areasize_divided:    new FormControl(''),
     });

这是我的HTML:

<mat-form-field>
         <input type="number"
         matInput
         formControlName="Areasize"
         placeholder="Area Size"
         (input)="calcAreaSize()"
         />
      </mat-form-field>

      <mat-form-field>
        <input type="number"
        matInput
        formControlName="Areasize_divided"
        placeholder="Area Size Divided"
        (input)="calcAreaSizeDivided()"
        />
     </mat-form-field>

这是我的TS,其中两个函数称为:

calcAreasize_divided()
    {
        this.formGroup.get('Areasize')
            .valueChanges
            .subscribe(value => this.formGroup
                .get('Areasize_divided')
                .setValue(isNaN(value) ? 0 : value / 100)
        );      
    }

calcAreasize()
    {
        this.formGroup.get('Areasize_divided')
            .valueChanges
            .subscribe(value => this.formGroup
                .get('Areasize')
                .setValue(isNaN(value) ? 0 : value * 100)
        );     
    }

还有其他方法可以做到吗?我尝试在onInit()上执行此操作,但收到相同的错误。

1 个答案:

答案 0 :(得分:1)

您要在一个输入更改中更改另一个输入值,这会导致堆栈已满,因此您可以这样操作:

  export class AppComponent  {
  formGroup: FormGroup;
  public buildyear=0;
  public areasize=0;


  constructor(){
    this.formGroup = new FormGroup({
        Buildyear:           new FormControl(this.buildyear, [Validators.minLength(4), Validators.maxLength(4)]),
        Areasize:            new FormControl(this.areasize, [Validators.required] ),
        Areasize_divided:    new FormControl(''),
     });
  }
  calcAreasizeDivided(){
            let value = this.formGroup.controls['Areasize'].value;
        this.formGroup
                .get('Areasize')
                .setValue(isNaN(value) ? 0 : value / 100)   
    }
calcAreasize(){
        let value = this.formGroup.controls['Areasize_divided'].value;
      this.formGroup.get('Areasize_divided').setValue(isNaN(value) ? 0 : value * 100) 
    }
}

html:

<form  [formGroup]="formGroup">
<mat-form-field>
         <input type="number"
         matInput
         formControlName="Areasize"
         placeholder=""
         (input)="calcAreasize()"
         />
      </mat-form-field>

      <mat-form-field>
        <input type="number"
        matInput
        formControlName="Areasize_divided"
        placeholder=""
        (input)="calcAreasizeDivided()"
        />
     </mat-form-field>
</form>

工作DEMO