如何使用ngFormModel将元素列表绑定到选择列表?

时间:2016-04-28 07:30:22

标签: angular angular2-forms angular2-formbuilder

假设我有一个表单组件,例如

export class FormComponent {
    form: ControlGroup;
    categories: AbstractControl;
    text: AbstractControl;
    private _categories: string[] = [ 'One', 'Two', 'Three' ];
    constructor(private _formBuilder: FormBuilder) {
        this.form = _formBuilder.group({
       'categories': [ this._categories ],
       'text': [ '', Validators.compose([ Validators.required, Validators.minLength(1) ]) ] 
    });
    this.categories= this.form.controls['categories'];
    this.text = this.form.controls['text'];
}

在我看来,我想要categories的下拉菜单和text的文字区域。文本区域很简单,

<form role="form" [ngFormModel]="form" (ngSubmit)="onSubmit(form.value)">
    <div class="form-group" [class.error]="!text.valid && text.touched">
        <textarea class="form-control" id="text" rows="5" placeholder="Text goes here" 
            [ngFormControl]="text"></textarea>
        <div *ngIf="!text.valid && text.touched" class="ui error message">
            Please enter some text.
        </div>
    </div>
</form>

但是我找不到任何关于如何使用select创建ngFormModel的示例,他们似乎都使用ngModel*ngFor循环来创建option 1}}具有ngValue属性的标记。这是否意味着我必须混合使用ngFormModelngModel或者是否有办法单独使用ngFormModel

1 个答案:

答案 0 :(得分:1)

您可以使用ngFormControl选择这种方式而不使用ngModel

<form [ngFormModel]="form">
  <div>
    <select test [ngFormControl]="form.controls.categories">
      <option *ngFor="#category of categories;#i=index" [value]="category.value">{{i}} - {{category.name}}</option>
    </select>
    categories : {{form.controls.categories.value}}
  </div>
</form>
<div (click)="updateValues()">Update values</div>

以下是组件的内容:

@Component({
  (...)
})
export class App {
  constructor(private builder:FormBuilder) {
    this.categories = [
      { name: 'Cat1', value: 'cat1' },
      { name: 'Cat2', value: 'cat2' },
      { name: 'Cat3', value: 'cat3' },
      { name: 'Cat4', value: 'cat4' }
    ];
    this.form = builder.group({
      categories: [ 'cat1' ]
    });
  }

  updateValues() {
    this.form.controls.categories.updateValue('cat3');
  }
}

请参阅此plunkr:https://plnkr.co/edit/2UItcrQQWr6eowsPoE4i?p=preview