Angular 表单根据下拉值添加输入字段

Angular Form add input field based on dropdown value

有谁知道如何显示基于 select 元素值的附加输入字段并将值推送到现有对象中?

有一个带有 change 指令的下拉 select 元素

<div class="col-sm-4">
  <select class="form-control mt-2" id="field_countries" name="country" #t formControlName="country" (change)="countryChanged(t.value)">
    <option [value]="country.name" *ngFor="let country of countries"> {{ country.name }} </option>
  </select
</div>

countryChanged事件

countryChanged(value) {
  this.selectedCountry = value;
  console.log(this.selectedCountry);
}

所以我正在尝试根据 selected 值添加新的输入字段:

<div class="col-sm-4" *ngIf="selectedCountry == 'Mexico'">
  <input type="text" class="form-control" name="remark" formControlName="remark" maxlength="200" />
</div>

但我不知道如何显示输入字段并仅为值是 selected 的对象推送值,所以结果将是

相当于[{person: 'John', country: 'USA'}, {person: 'Pablo', country: 'Mexico', remark: 'Some data'}, {person: 'Michelle', country: 'France'}]

Stackblitz

我稍微修改了你的堆栈闪电战:在此处查看:https://stackblitz.com/edit/select-populate-values-kyirzw?file=app%2Fapp.component.ts

在初始化 FormGroup 时,我没有默认添加 remark FromControl。

  getFormGroupByN(n: number) {
  let result = [];
  for (let i = 0; i < n; i++) {
    result.push(this.formBuilder.group({
      'person': '',
      'country': ''
    })
    );
  } // for end 

  return result;
}

我修改了您的 countryChanged() 方法,它现在也接受 FormArray 的 index。现在,每当我看到所选国家/地区是 Mexico 时,我都会在 index.

处向该特定 FormGroup 添加一个 FormControl remark
countryChanged(value, i) {
  this.selectedCountry = value;
  // this.getFormGroupByN(this.personsData.length);  // why were you calling this again?
  if (value == "Mexico") {
    let temp =  <FormGroup>(<FormGroup>this.selectForm.get('persons')).controls[i];
    temp.addControl('remark', new FormControl(''));
  }
}

用于显示备注输入框的 HTML 现在正在检查是否存在 remark formControl 而不是 CountryName

<div class="col-sm-4" *ngIf="selectForm.get('persons').controls[i].get('remark')">
   <input type="text" class="form-control" name="remark" formControlName="remark" maxlength="200" />
</div>

将当前值与您已声明为“t”的模板引用变量匹配,如下所示:

*ngIf="t.value == 'Mexico'" 这里:

<div class="col-sm-4" *ngIf="t.value == 'Mexico'">
  <input type="text" class="form-control" name="remark" formControlName="remark" maxlength="200" />
</div>

然后你可以使用一些 ES6:

删除提交函数中的空白属性
  onSubmit() {
    this.persons = this.selectForm.get('persons') as FormArray;
    const temp: any = this.persons.value;
    temp.forEach((v) => {
      Object.keys(v).forEach((key) => (v[key] == '') && delete v[key]);
    })
    console.log(temp)
  }

Stackblitz