2017-05-01 69 views
3

我已经做了一些研究,我很惊讶地发现它并不像应该那样直截了当。如何使用formBuilder绑定angular2中的选择下拉列表?

我知道有一些使用ngModel的方法。像Bind and fetch dropdown list value in typescript and Angular2等。但我想能够轻松地将我选择的选项绑定到我的formControlName var。

这是我曾尝试:

.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"} 
    ]; 

默认值的作品。但是当我选择BB时,默认值仍然被选中。 同当Bind Select List with FormBuilder Angular 2

我在做什么错误的默认值是“”

建议这个方案是由哈利 - 广宁发生什么呢?

注意:当然,还有其他输入形式,为了简单起见,忽略它们。

编辑

我试图用这个plunkr完全相同的例子,它也不管用。 http://plnkr.co/edit/Rf9QSSEuCepsqpFc3isB?p=preview 发送表单后,表明该值没有被触及。

debug info

+0

你检查此[链接](http://stackoverflow.com/questions/39689049/drop-down-list-in-angular-2-model-driven-form) –

回答

5

您好我请做如下

<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> 

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

而且我也创建工作plunkr

希望这将帮助你

+0

感谢您的回答。知道我明白为什么它不起作用。即使这在你提供的plunkr中完美工作。但是我在这里有一个小问题...'property'name'不存在于类型'{name:string; } [''它根本没有任何意义,因为当我检查pref var时,它清楚地表明它有一个名为“name”的属性,为什么可能在那里发生? –

+0

你有更新你的代码吗?如果是,那么你能更新你在这里试过的东西吗?并发布错误的截图。 –

相关问题