3

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

Community
  • 1
  • 1
Joan Gil
  • 145
  • 3
  • 10

1 Answers1

6

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

The Hungry Dictator
  • 3,444
  • 5
  • 37
  • 53
  • Thanks for your answer. Know I see why it did not work. Even when this works perfectly in the plunkr you provided. But I have a little issue here... `Property 'name' does not exist on type '{ name: string; }[]'` It does not make any sense at all because when I inspect pref var, it clearly says it has a property named "name", why could be happening there? – Joan Gil May 01 '17 at 22:56
  • Have you updated your code? If yes then can you update what you have tried over here? And also post screenshot of your error. – The Hungry Dictator May 02 '17 at 03:47