Angular2 - 在select中设置初始值 - Reactive表单

时间:2017-03-06 08:08:28

标签: javascript angular

我在select中设置默认选项时遇到问题。我从服务器获取数组,我想在数组中选择documentTypes [1]中的第二项。这是我的代码以及我尝试做的事情。

选择HTML

<select formControlName="type">
    <option *ngFor="let document of documentTypes" [ngValue]="document" [attr.selected]="selectedType">{{document.name | translate}}</option>
</select>

来自服务器的值

getDocumentTypes() {
    this._api.send(urlValues.documentType, 'Get').subscribe(
        res => {
            this.selectedType = res.content.types[1];
            this.documentTypes = res.content.types;
        },
        err => console.log(err)
    );
}

我也有构建文档方法,我尝试了这个

buildDocument(document?: any) {
    if (document) {
        this.documentForm = this._fb.group({
            customer: this._fb.group({
                oib: document.customer.oib,
                location: document.customer.location
            }),
            payment_method: document.payment_method,
            delivery_method: document.delivery_method,
            status: document.status,
            type: document.type,
            expiration_date: document.expiration_date,
            delivery_date: document.delivery_date,
            note: document.note
        });
    } else {
        this.documentForm = this._fb.group({
            customer: this._fb.group({
                oib: null,
                location: null
            }),
            payment_method: null,
            delivery_method: null,
            status: null,
            type: this.documentTypes[1],
            expiration_date: '',
            delivery_date: '',
            note: ''
        });
    }
}

您还有其他解决方案吗?感谢

2 个答案:

答案 0 :(得分:2)

使用formControl而不是[attr.selected]。也许您还需要使用例如patchValue,因为数据是异步的并且在检索数据后设置预选值,以便在数据不存在时尝试构建表单时应用程序不会引发错误。

所以你的选择看起来像这样:

<select name="document" formControlName="type">
    <option *ngFor="let doc of documentTypes" [value]="doc.name">  
        {{doc.name}}
    </option>
</select>

当您收到API中的数据时,您可以使用patchValue

  this.documentForm
    .patchValue({
        type: this.documentTypes[1].name
    })

这是一个 demo plunker ,其中Set Value按钮类似于模拟数据异步,只是为了展示patchValue:)

<强> PS:

如果需要绑定整个对象,可以使用ngValue,但这也意味着您的表单值将包含整个对象,类似于:

{
  "type": {
    "id": 2,
    "name": "Doc 2"
  }
}

也许那不是你想要的,所以我在这里只使用name,所以你的表格价值如下:

{
  "type": "Doc 3"
}

答案 1 :(得分:0)

试试这个:

getDocumentTypes() {
    this._api.send(urlValues.documentType, 'Get').subscribe(
        res => {
            this.selectedType = res.content.types[1];
            this.documentTypes = res.content.types;
            this. documentForm.patchValue({'type': res.content.types[1]}, {onlySelf: true}) //Add this line
        },
        err => console.log(err)
    );

}

相关问题