如何设置Angular 2 Reactive Select的初始值

时间:2017-02-01 08:07:16

标签: angular angular2-forms angular2-formbuilder

我有一个选择列表,我想要初始化从服务器返回的保存值。但无论我尝试什么,我都无法使用所选的值。

我使用的是Angular 2.2.0 Reactive Forms

以下是选择列表的值列表。

private categoryList: ICategory[] = [
    new Category({ id: 1, name: 'Cat 1' }),
    new Category({ id: 2, name: 'Cat 2' }),
    new Category({ id: 3, name: 'cat 3' })
];

保存的值为:

{ id: 1, name: 'Cat 1' }

使用FormBuilder我创建表单

   this.itemForm = this.fb.group({
      name: [null, Validators.required],
      description: [null, Validators.required],
      weight: [null, Validators.required],
      dimensions: [null, Validators.required],
      category:  [null, Validators.required] 
    });

然后我使用保存的数据

初始化它
  (<FormGroup>this.itemForm)
        .setValue({
          name: item.name,
          description: item.description,
          weight: item.weight,
          dimensions: item.dimensions,
          category: item.category 
        }, { onlySelf: true });

模板看起来像这样

<select name="category" [formControl]="itemForm.controls['category']">
         <option [selected]="itemForm.controls['category'].value == null" value="">-- Select --</option>
        <option *ngFor="let cat of categories" [ngValue]="cat">  
            {{cat.name}}
        </option>
    </select>
{{itemForm.controls['category'].value | json }}

预期结果 在选择中选择第一项的名称,并匹配模板

下显示的JSON中的文本

实际行为 JSON显示了这个:

 { "id": 1, "name": "Cat 1" }

但是在选择

中没有选择任何内容

如果选择--Select--则JSON会正确更新为“”。

如果选择了另一只猫,JSON也会正确更新。

  

我做错了什么,如何初始化选择?

EDIT 我也试过这个:

<option *ngFor="let cat of categories" [selected]="itemForm.controls['category'].value.id == cat.id" [ngValue]="cat">

3 个答案:

答案 0 :(得分:5)

如果我理解正确,您需要设置默认值。然后,您可以参考您的item.category +您要设置的值的索引。

我会设置这样的值,我们将第一项设置为默认值。

setValues() {
    this.itemForm
        .setValue({
            name: item.name,
            category: item.category[0].id
        })
}

然后在表单中使用formGroupformControlName,所以:

<form [formGroup]="itemForm">
  <input formControlName="name"/>
  <small *ngIf="!itemForm.controls.name.valid">Name is required!</small>
  <!-- More code -->
  <select formControlName="category">
    <! -- set ngValue to cat.id --> instead of just cat!
    <option *ngFor="let cat of categories" [ngValue]="cat.id">  
      {{cat.name}}
    </option>
  </select>
</form>

根据您要使用的内容,将[ngValue](或仅使用[value])设置为cat.namecat.id,因此如果您使用的是{{1} },它不会绑定整个对象!

这是一个有效的Plunker 。不知道你在哪里设置值,此时,我在plunker中创建了一个ngValue - 按钮,模仿了以后设置的值。

希望这有帮助!

答案 1 :(得分:0)

尝试使用[attr.selected]和[attr.value]代替[selected]和[ngValue]。

答案 2 :(得分:0)

试试这段代码。它正在使用Angular 5

<select formControlName="category">
 <option [ngValue]="undefined" selected disabled>Select Type</option>
    <option *ngFor="let cat of categories" [ngValue]="cat.id">  
      {{cat.name}}
    </option>
  </select>
相关问题