我有一个充满项目和值的动态数组
。当用户单击项目上的按钮时,它应该从 View 列表中删除该项目。我完全猜不到这是为什么。数据的结构如何?我不这么认为,因为它表明它正在控制台中被删除。无论如何,谢谢!
TS:
export class Page{
items: Item[];
constructor(public alertCtrl: AlertController){}
removeitem(i) {
let confirm = this.alertCtrl.create({
title: 'Confirm',
message: "text.",
buttons: [
{
text: 'Cancel',
handler: () => {
console.log('Disagree clicked');
}
},
{
text: 'Save',
handler: () => {
this.presentToast()
this.items.splice(i, 1);
}
}
]
});
confirm.present();
}
getItems(){
this.stopService.getItems().subscribe(item => {
this.items = item
})
}
}
HTML:
<div *ngFor="let item of items; index as i ">
<h3>{{item.description}}</h3>
<button item-end ion-button full (click)="removeitem(i)">remove item</button>
</div>
编辑
添加服务如何获取项目 --
getItems(): Observable<any> {
return this.http.get(someEndpoint)
.map(res => res.json());
}
最佳答案
尝试执行以下操作:
removeitem(i) {
let confirm = this.alertCtrl.create({
title: 'Confirm',
message: "text.",
buttons: [
{
text: 'Cancel',
handler: () => {
console.log('Disagree clicked');
}
},
{
text: 'Save',
handler: () => {
this.presentToast()
this.items = [...this.items.filter((item, index) => index !== i];
}
}
]
});
confirm.present();
}
这完全改变了对象引用并且应该触发 DOM 更新。
如果这不起作用,请尝试将您的拼接包装在 setTimeout 中:
setTimeout(() => { this.items.splice(i, 1); }, 0);
你也可以尝试在构造函数中注入(inject)public zone: NgZone
然后运行
在 this.zone.run(() => { this.items.splice(i, 1); });
中拼接。这是另一种强制更改检测的方法。
编辑:
在您的 getItems()
方法中,尝试这样做:
getItems() {
this.stopService.getItems().subscribe(item => {
this.items = [...item];
});
}
Plunker 引用:
关于angular - 数组未在 DOM 中拼接,但在控制台中是 - Ionic 2+/Angular2+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764391/