![](/img/trans.png)
[英]How can i bind ngModel value with options list of dropdown in angular 2?
[英]bind the json value in ngmodel in angular 2
這是我的json響應。 如何在角度2中綁定[(ngModel)]
中的rewards.rewardName值。
[
{
"id": 18,
"gname": "learning ramayanam",
"goalCategory": "Education",
"goalSubCategory": "short-term",
"goalDesc": "good",
"rowStatusCode": "D",
"createID": "1",
"createTS": null,
"updateID": "Ram",
"updateTS": null,
"rewards": {
"rewardID": 1,
"rewardName": "Laptop"
}
]
這是我的代碼伙伴,我如何綁定ngModel中的值
ngOnInit() {
this.route.params
.forEach(params => {
this.isEdition = !!params['id'];
if (this.isEdition) {
// this.getDocument(params['id']);
this.itemPromise = this.http.get('http://localhost:8080/dy/get-goal?id='
+
params['id'])
.map(res => res.json()).toPromise();
this.itemPromise.then((item: any) => {
console.log(item);
var arr = JSON.parse(item);
this.item = arr[0];
return item;
});
我建議您看一下官方的http教程 。 我建議您使用Promise或Observable。 似乎您想使用Promise,因此我將為您設置該示例。 另外,請考慮使用推薦的服務(如本教程中所述),但是在這里,我將使用您現有的代碼:
// remove "this.itemPromise = " and just have the code below
this.http.get('http://localhost:8080/dy/get-goal?id=' + params['id'])
.toPromise()
.then(res => res.json())
.then(data => {
this.item = data[0];
})
完成此操作后,將出現undefined
問題,因為這是異步的。 請檢查以下一項: 無法讀取未定義的雙向綁定的屬性“ totalPrice” ,即[(ngModel)]
不支持安全的導航運算符,因此您希望將其拆分為單向綁定和ngModelChange
:
<input [ngModel]="item?.rewards?.rewardName"
(ngModelChange)="item?.rewards?.rewardName ? item.rewards.rewardName=$event : null" >
對此的支持: https : //stackoverflow.com/a/36016472/6294072
這是一個使用服務的DEMO ,建議您這樣做;)
將您的json解析為一個對象。
var obj = JSON.parse(json);
然后將其綁定到您的元素
[(ngModel)]="obj.rewards.rewardName"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.