【问题标题】:Form keeps on re-rendering when updating formArray values angular form更新 formArray 值 angular form 时,Form 不断重新渲染
【发布时间】:2020-01-08 06:44:38
【问题描述】:

我在 Angular 的表单中创建一个子表单。 https://codesandbox.io/s/distracted-cohen-4r1qd

表单在添加某些输入时不断重新呈现。

这里是代码

<form class="nlsg-c-form-element" [formGroup]="insuranceForm">
  <div class="account-details accountDetails" formArrayName="ownerNames">
    <h6>Additional policy details</h6>
    <!-- owner name -->
  <div
  class="row"
  *ngFor="let ownerName of insuranceForm.controls.ownerNames?.value;let i = index"
>
     <div class="col">
     <div class="nlsg-c-form-element__form-group" [formGroupName]="i">
        <label
        class="nlsg-c-form-element__label"
        [innerHtml]="'Owner name'"
      ></label>
      <input
        class="nlsg-c-form-element__control"
        type="text"
        formControlName="name"
      />
    </div>
  </div>

  <div class="col forMargin">
    &nbsp;
  </div>

  <div class="col" [formGroupName]="i">
    <span
      class="trash"
      [hidden]="!insuranceForm.controls.ownerNames.controls[i].controls.name.value"
    >
    </span>
    <span
      class="trashGray"
      [hidden]="insuranceForm.controls.ownerNames.controls[i].controls.name.value"
    >
    </span>
  </div>
</div>

 insuranceForm: FormGroup;

   constructor(private fb: FormBuilder) {}

   ngOnInit() {
    this.initializeForm();
  }

 initializeForm() {
   this.insuranceForm = this.fb.group({
     productName: [null, Validators.required],
     policyNumber: [null, Validators.required],
     insuranceType: [null, Validators.required],
     coverAmount: [null, Validators.required],
     premiumAmount: [null, Validators.required],
     frequency: [null, Validators.required],
     dueDate: [null, Validators.required],
     instExpDate: [null, Validators.required],
     companyCode: [null, Validators.required],
     ownerNames: this.fb.array([])
   });
   this.addOwnerNameField();
 }

 addOwnerNameField() {
   const ownernameArray = this.insuranceForm.controls.ownerNames as FormArray;
   ownernameArray.push(
     this.fb.group({
       name: ""
     })
   );
 }

只要我在文本框中输入文本,它就允许我只添加 1 个字符,然后从该文本框中聚焦。

我认为 Form 的 UI 会在我每次输入内容时重新加载。

【问题讨论】:

    标签: angular forms subform


    【解决方案1】:

    我从朋友那里得到的。

    我正在迭代值而不是控制。

    更改代码
    *ngFor="let ownerName of insuranceForm.controls.ownerNames?.value;let i = index"
    

    *ngFor="let ownerName of insuranceForm.controls.ownerNames?.controls;let i = index"
    

    一切都完成了。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多