Search code examples
angulartypescriptangular-formsformarrayangular-formbuilder

Angular Form add input field based on dropdown value


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


Solution

  • Match current value with template ref variable that u have declared as "t" like this:

    *ngIf="t.value == 'Mexico'" here:

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

    and then you can remove blank attributes in submit function with some 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