Nouman Bhatti
Nouman Bhatti

Reputation: 1421

Angular: Adding events to FormControls added dynamically in FormArray

I'm using Angular 4 and I'm creating a page where user can create a format consists of Hash, sequence and constant value. User can add them in any order,so for this purpose I'm creating them dynamically using FormArray

HTML Code is:

 <div formArrayName="components"
    *ngFor="let c of components.controls; let i=index">
   <div [formGroupName]="i">
     <div class="form-group row">
       <div class="col-md-3">
         <select type="" id="component" class="form-control" placeholder="" 
             formControlName="component">
           <option value="Sequence">Sequence</option>
           <option value="Hash">Hash</option>
           <option value="Constant">Constant</option>
         </select>
       </div>
       <div class="col-md-2">
        <input type="number" class="form-control" formControlName="limit" />
       </div>
       <div class="col-md-4">
        <input type="text" class="form-control" formControlName="value" />
       </div>
       <div class="col-md-2" style="color:red" (click)="deleteRow(i)">
           <fa name="times"></fa>
       </div>
      </div>
    </div>
  </div>

The code above will produce an output like this. enter image description here

Question How to bind events with these dynamically created controls? For example on selection of certain value in drop down I want to hide the input control next to it.

Upvotes: 1

Views: 2033

Answers (1)

Enas Osama
Enas Osama

Reputation: 211

You can bind the event to a function that takes the index and then retrieve the controls from the formArray in the function using the index

In your HTML

 <select type="" id="component" class="form-control" placeholder="" 
             formControlName="component" (change)="onChange(i)>

In your ts file

let row = components.controls[pos] as FormGroup 
//row now contains all the controls bound to it you can access the controls like the following 
let value = row.controls["component"].value

Or if you just want to hide the input without any complex conditions you can try this in your HTML

 <input type="number" class="form-control" formControlName="limit" *ngIf="c.get('component').value != 'whatever'"/>

Upvotes: 1

Related Questions