4

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

我正在使用 Angular 2.2.0Reactive 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 }}

预期结果 select 中选择了第一项的名称,并与模板下显示的 JSON 中的文本匹配

实际行为 JSON 显示了这一点:

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

但是选择中没有选择任何内容

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

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

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

编辑我也试过这个:

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

3 回答 3

5

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

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

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

然后使用formGroupandformControlName形式,所以:

<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.name或者,因此如果您正在使用,则不会绑定整个对象!cat.idngValue

这是一个工作Plunker。不知道您在哪里设置值,此时,我在setValuesplunker 中制作了一个 - 按钮,以模拟稍后设置的值。

希望这有帮助!

于 2017-02-01T11:54:28.527 回答
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>
于 2018-02-08T10:50:57.923 回答
0

尝试使用 [attr.selected] 和 [attr.value] 而不是 [selected] 和 [ngValue]。

于 2017-02-01T08:28:29.997 回答