gpt4 book ai didi

javascript - Angular2 - 在选择中设置初始值 - react 形式

转载 作者:行者123 更新时间:2023-11-30 15:28:21 25 4
gpt4 key购买 nike

我在选择中设置默认选项时遇到问题。我正在从服务器获取数组,我想选择数组中的第二项,即 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: ''
});
}
}

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

最佳答案

使用 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 :)

附言:

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

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

也许这不是你想要的,所以我在这里只使用 name,所以你的表单值看起来像这样:

{
"type": "Doc 3"
}

关于javascript - Angular2 - 在选择中设置初始值 - react 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42620498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com