Angular 响应式表单:- 在动态行中动态填充输入

Angular Reactive Form: - Fill Input dynamically in Dynamic rows

我正在开发一个注册模块,用户可以在其中添加多个频道,例如 google、yahoo、outlook 和自定义。

问题:-

  1. 自定义 Url 字段的 OnSelection 将为空,如果是其他域,url 字段将被预填充。
  2. 如果您 select 在域中自定义,则 URl 字段需要为空白且可编辑。
  3. 如果我点击添加更多,那么表单需要像加载页面时一样空白。

我在 https://angular-db4rzu.stackblitz.io 创建了虚拟表格。寻求帮助。

您的项目中出现了一个严重的循环,您订阅表单更改的方式,然后根据发射更新 FormControl 值。

本质上,您将更改表单中的值,它将通过 valueChanges 订阅触发 scmTypeCheck(),这将设置新值,然后通过 valueChanges 发出另一个更改,并且触发 scmTypeCheck() 一次又一次...

然后单击 Add More Row 使情况变得更糟,因为循环呈指数增长,最终超过调用堆栈限制。

In my Stackblitz example I replaced your valueChanges subscription with selectionChange event on your mat-select... this ensures there is no loop and your FormControl values are only updated once.

我还用以下内容替换了您的整个 scmTypeCheck() 逻辑。

setDomainName(i, value) {
  //get the index of the selected value in the scmDummyStructure to use for default values
  const index = this.scmDummyStructure.findIndex(x => x.type === value);
  //get the url control to set state and default on user change
  const urlControl = this.scmForm.get('scmDatas')['controls'][i].get('url');

  //set default value
  urlControl.setValue(this.scmDummyStructure[index].url);

  //if custom type enable and clear any existing value if field not pristine else disable
  if (value === 'custom') {
    if (!urlControl.pristine && urlControl.value != '') {
      urlControl.setValue('');
      urlControl.enable();
    }else{
      urlControl.enable();
    }
  } else {
    urlControl.disable();
  }
}

Stackblitz

https://stackblitz.com/edit/angular-b7bjj6?embed=1&file=src/app/app.component.ts