Angular2 - 在select中设置初始值 - 反应形式
问题描述:
我在select中设置默认选项时遇到问题。我从服务器获取数组,我想选择数组中的第二个项目,即documentTypes [1]。这是我的代码和我试图做的。Angular2 - 在select中设置初始值 - 反应形式
选择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: ''
});
}
}
您有其他解决方案吗?由于
答
利用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:
{
"type": {
"id": 2,
"name": "Doc 2"
}
}
,也许:
,如果你需要将整个对象绑定,但是这也意味着你的表格值将包含整个对象,与此类似,您可以使用ngValue
这是不是你想要的,所以我只用name
在这里,所以你的形式值如下:
{
"type": "Doc 3"
}
答
试试这个:的
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)
);
}
一个plunkr将是非常有用的。 –
这就是'if(document){'for?第二(else)分支事件是否被执行? –
如果(文档)用于编辑表单,当我获得现有的文档数据并填写表单时,我只需调用buildDocument(document)@GünterZöchbauer –