Angular Form add input field based on dropdown value

corry picture corry · Oct 2, 2018 · Viewed 7.7k times · Source

Does anyone have idea how to show additional input field based on select element value and push value into existing object?

There is a dropdown select element with change directive

<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>

and countryChanged event

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

so I'm trying to add new input field based on selected value:

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

but I don't know how to show input field and push value only for object which value is selected for, so the result would be enter image description here

equivalent to [{person: 'John', country: 'USA'}, {person: 'Pablo', country: 'Mexico', remark: 'Some data'}, {person: 'Michelle', country: 'France'}]

Stackblitz

Answer

Ashish Ranjan picture Ashish Ranjan · Oct 2, 2018

I modified your stack blitz a little: See it here: https://stackblitz.com/edit/select-populate-values-kyirzw?file=app%2Fapp.component.ts

While Initilizing the FormGroup, I didn't add the remark FromControl by Default.

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

  return result;
}

I modified the countryChanged() method of yours, which now also accepts an index of the FormArray. Now whenever I see that the country selected was Mexico I add a FormControl remark to that particular FormGroup at that 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(''));
  }
}

The HTML for showing Input box for Remarks is now checking for the presence of the remark formContrl instead of the 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>