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

时间:2018-10-02 11:41:15

标签: angular typescript angular-forms formarray angular-formbuilder

有人知道如何根据选择元素值显示附加输入字段并将值推入现有对象吗?

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

<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);
}

所以我试图根据所选值添加新的输入字段:

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

但是我不知道如何仅显示选择值的对象的输入字段和推送值,因此结果将是 enter image description here

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

Stackblitz

2 个答案:

答案 0 :(得分:1)

我对堆栈闪电进行了一些修改:请在此处查看: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时,我都会在该remark处的特定FormGroup中添加一个FormControl index

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 formContrl而不是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>

答案 1 :(得分:0)

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

*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