[英]How do I update a dynamic span using ngModel in Ionic?
I'm trying to update dynamic items in my Ionic app;我正在尝试更新 Ionic 应用程序中的动态项目; I want to update a number (quantity) when the
addItem()
function is called.我想在调用
addItem()
function 时更新一个数字(数量)。 I can't figure out how to update quantity
so that I can update each one in my list based on their key.我不知道如何更新
quantity
,以便我可以根据它们的键更新列表中的每一个。
<ion-item *ngFor="let item of collection.items">
<span [(ngModel)]="quantity[item.id]" name="quantity[{{ item.id }}]" ngDefaultControl>
{{ item.quantity }}
</span>
</ion-item>
quantity = [];
constructor() {}
addItem(itemId: any) {
const body = new FormData();
body.append('item_id', itemId);
this.http
.post('http://api.example.com/endpoint', body)
.subscribe(
(response: any) => {
const data = {
key: itemId,
value: response.item_quantity
};
// how do I get the returned value from the API
// to display in my span?
this.quantity.push(data);
},
error => {}
);
}
You can do this in two ways你可以通过两种方式做到这一点
One:一:
<ion-item *ngFor="let item of collection.items">
<span>
{{ getItemQuantity(item.id) }}
</span>
</ion-item>
Two:二:
<ion-item *ngFor="let item of collection.items">
<span [innerHTML]="getItemQuantity(item.id)">
</span>
</ion-item>
And It is necessary to detect change in addItem call like this:并且有必要像这样检测 addItem 调用的变化:
import { ChangeDetectorRef } from '@angular/core';
public quantity: array = [];
public cdRef: ChangeDetectorRef;
constructor(cdRef: ChangeDectorRef) {}
getItemQuantity(itemId: any): number {
if (this.quantity.length === 0) {
return 0;
}
return this.quantity.find(q => q.key === itemId).value;
}
addItem(itemId: any) {
const body = new FormData();
body.append('item_id', itemId);
this.http
.post('http://api.example.com/endpoint', body)
.subscribe(
(response: any) => {
const data = {
key: itemId,
value: response.item_quantity
};
this.quantity.push(data);
this.cdRef.detectChanges(); // here you need to detect change
},
error => {}
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.