How can I bind selection in angular2 using formBuilder?
I've done some research, and I'm surprised it's not as straightforward as it should be.
I know there are some approaches using ngModel. How to Bind and select dropdown list in typescript and Angular2 and others. But I want to be able to easily bind my selected parameter to my formControlName var.
Here's what I've 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 works. But when I select BB, the default is still selected. The same happens when the default is ''
This approach is suggested by Harry-ninh in the Bind Select List with FormBuilder Angular 2
What am I doing wrong?
Note: of course there are other inputs in the form, just ignored them for simplicity.
EDIT
I tried to use the same example in this plunkr and it doesn't work either. http://plnkr.co/edit/Rf9QSSEuCepsqpFc3isB?p=preview After submitting the form, it shows that the value has not been touched.
source to share
Hello please do as follows
<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 also created a working plunkr .
Hope this helps you
source to share