1
votes

How do you build a select using formbuilder,formgroup in angular 2?

Currently what I thought of is having a option with *ngFor that loops through a list that I have created and than when an option is selected it updates the FormControl with the value that i got in my select.

HTML

<form [formGroup]="myForm" (ngSubmit)="submit()">
    <select  class="form-control"  >
      <option *ngFor="let pos of tabpositing" formControlName="tabposition" [value]="pos.name">{{pos.name}}</option>
    </select>
</form>

<div  style="  height: 150px; overflow: scroll;">
<pre><code>{{ myForm?.value | json }}</code></pre></div>
<div style="  height: 150px; overflow: scroll;">
       <pre> {{ widget | json }}</pre>
</div>

TS

public tabpositing: any  = [
                          {name: 'top', value: false},
                          {name: 'right',value: false},
                          {name: 'bottom',value: false},
                          {name: 'left',value: false}
                        ]
constructor(public _fb: FormBuilder) { }
this.myForm = this._fb.group({
 tabposition: new FormControl(''),
}),

Other option I thought is having a function that runs through a loop and created the formControl etc, but could not figure out how to get the HTML for the select

let tabpos : FormArray = new FormArray([]);
             for (let i = 0; i < this.tabposition.length; i++) {
                let fg = new FormGroup({});
                fg.addControl(this.tabposition[i].name, new FormControl(this.tabposition[i].value))
                tabpos.push(fg)
              }

 this.myForm = this._fb.group({
tabposition: tabpos

  });
1

1 Answers

1
votes

Hi to do this you can leave your option tag as it is and in the select do something like

<select  class="form-control"  formControlName="tabposition"  >
      <option *ngFor="let pos of tabpositing" [value]="pos.name">{{pos.name}}</option>
</select>

and

this.form = this.fb.group({
  tabposition: ''
});

The selected option will be converted into a string and be under form.controls.tabposition

If you wanna do something when the select changes just add

<select  (ngModelChange)="myFunction($event)"  class="form-control"  formControlName="tabposition"  >
      <option *ngFor="let pos of tabpositing" " [value]="pos.name">{{pos.name}}</option>
</select>

to the select and the corresponding fucntion on the component