首页 > 解决方案 > 动态设置输入仍然使表单无效

问题描述

我有三个输入框都是必需的。第一个输入框是手动输入的数量,第二个是基于第一个输入(数量/总计)的(输入)方法计算的,第三个输入是动态设置的总计(来自DB)。这些输入的动态设置工作正常。但是在自动设置计算和总计之后,表单仍然无效,我怎样才能使表单有效,因为两个框已经有值,这些值是动态设置的。

form.component.html

<mat-form-field class="w-10-p" appearance="outline">
     <input  matInput 
         formControlName="quantity" 
         type="number"
         (input)="computeValues(i, $event)"
         required>
</mat-form-field>

<mat-form-field class="w-10-p" appearance="outline">
     <input  matInput 
          formControlName="computed" 
          [id]="'computed'"
          type="number"
          required> 
</mat-form-field>

<mat-form-field class="w-10-p" appearance="outline">
      <input  matInput 
            formControlName="total" 
            [id]="'total'"
            type="number"
            required> 
</mat-form-field>

form.component.ts

computeValues(index,event){ //iluvJS
        var quantity=event.target.value;
        let total = (document.getElementById('total') as HTMLInputElement).value;
        var size = Math.round((parseFloat(total) / quantity) * 100) /100;
        (document.getElementById('size') as HTMLInputElement).value=size.toString();

    }

表单仍然表现得好像这些输入仍然是空的。

标签: javascriptangular

解决方案


您必须这样做(如果您必须更新某些控件,请使用patchValue ,如果您想更改所有控件,请使用setValue )

this.yourForm.patchValue({
  total: 50,
  size: '123'
})

推荐阅读