Joan Gil
Joan Gil

Reputation: 145

How can I bind select dropdown in angular2 using formBuilder?

I've done some research and I'm surprised to know it's not as straight-forward as it should be.

I know there are some approaches using ngModel. Like Bind and fetch dropdown list value in typescript and Angular2 and others. But I want to be able to easily bind my selected option to my formControlName var.

This is what I have tried:

.HTML

 <form id="myForm" name="father" [formGroup]="fatherForm" (ngSubmit)="createFather()">
     <div class="row">
         <select formControlName="pref" id="f">
              <option value=null disabled selected>Prefijo</option>
              <option *ngFor="let item of prefs" [ngValue]="hola">{{item.name}}</option>
          </select>

      </div>
 </form>

.TS

fatherForm: FormGroup;  

this.fatherForm = this.formBuilder.group({
          pref: ['AA']
});

 this.prefs=[
     {name: "AA"},
     {name: "BB"}
  ];

The default value works. But when I choose BB, the default value is still selected. Same happens when default value is ''

This approach is suggested by Harry-ninh in Bind Select List with FormBuilder Angular 2

What am I doing wrong?

Note: of course, there are other inputs in form, just ignored them for the sake of simplicity.

EDIT

I tried using the exact same example in this plunkr and it does not work either. http://plnkr.co/edit/Rf9QSSEuCepsqpFc3isB?p=preview After form is sent, it shows that value has not been touched.

debug info

Upvotes: 3

Views: 5367

Answers (1)

The Hungry Dictator
The Hungry Dictator

Reputation: 3484

Hi I please do as following

<form id="myForm" name="father" [formGroup]="fatherForm">
   <div class="row">
     <select formControlName="pref" id="f">
          <option value=null disabled selected>Prefijo</option>
          <option *ngFor="let item of prefs" [value]="item.name">{{item.name}}</option>
      </select>

  </div>
   <button type="submit">Submit</button>
</form>
<p>Value: {{ fatherForm.value | json }}</p>

and

name:string;
fatherForm : FormGroup;
prefs=[
 {name: "AA"},
 {name: "BB"}
];
constructor(fb:FormBuilder) {
  this.fatherForm = fb.group({
    pref : [this.prefs.name]  
 });
}

And I have also created working plunkr.

Hope this will help you

Upvotes: 6

Related Questions