Angular 2 Reactive Forms - Binding fetches dropdown value in reactive form array form

I have created a reactive form that has an array of the form. A group of forms is entered into the form array by pressing a button. This way, every click on the button creates an html section on the screen.

This form group contains 2 drop-down lists that have a parent-child relationship, that is, selecting an item in the drop-down list of the parent item decides the values ​​to be filled in the drop-down list.

When I select a value in the parent dropdown menu, the event event retrieves the results for the child, but this must be scoped to the specific element of the form array. Currently changing events fetches data and sets values ​​for child dropdowns in each element of the form array. This is the basic structure of my labeling

<form [formGroup] = "mainForm" (ngSubmit)="savedata()">
<div>some form control</div>
<div formArrayName = "myArray" *ngFor="let arrayitem of myArray.controls";let i = index">
<div [formGroupName] = "i">
<div>
 <select class="form-control" (change)="onSelect($event.target.value)" id="{{'header' + i}}" formControlName="parentdrpdown">
 <option value="" disabled selected hidden>Select a Parent...</option>
 <option *ngFor="let pitem of parentdrpdown"
         value={{pitem.id}}>
         {{pitem.name}}
 </option>
 </select>
</div>
<div>
 <select class="form-control" (change)="onSelect($event.target.value)" id="{{'header' + i}}" formControlName="childdrpdown">
 <option value="" disabled selected hidden>Select a Child...</option>
 <option *ngFor="let citem of childdrpdown"
         value={{citem.id}}>
         {{citem.name}}
 </option>
 </select>
</div>
</div>    
</div>

constructor(private fb: 
 FormBuilder, private _segService: SegmentService) {
    this.parentdrpdown= this._segService.getparentValues();

onSelect(pid) {
    this.childdrpdown= this._segService.getChildSegment()
        .filter((item) => item.parentid == pid);
 }

      

parentdrpdown and childdrpdown are properties declared in the component and they are loaded with values ​​using an http get request to the web server.

+3


source to share


1 answer


Use below code snippet for reactive form in case of select tag.



<h1>My Application</h1>
<select formControlName="selectedValue">
   <option *ngFor="let c of countries" [ngValue]="c">{{c.name}}</option>
</select>

      

+1


source







All Articles