首页 文章

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

提问于
浏览
3

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

我正在使用Angular 2.2.0Reactive Forms .

Here is list of values for the select list.

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

The saved value is:

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

Using FormBuilder I create the form

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] 
    });

I then initialise it with the saved data

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

The template looks like this

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

Expected Result 在选择中选择了第一项的名称,并匹配模板下显示的JSON中的文本

Actual Behaviour 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">

3 回答

  • 0

    如果我理解正确,您需要设置默认值 . 然后你可以参考你想要设置的值的索引 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 ,具体取决于您要使用的内容,因此如果您使用 ngValue ,则不会绑定整个对象!

    Here is a working Plunker . 不知道你在哪里设置值,此时,我在plunker中创建了一个 setValues -按钮,模仿了以后设置的值 .

    希望这有帮助!

  • 0

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

  • 5

    试试这个代码 . 它正在使用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>
    

相关问题