I have a dynamic array
full of items and values. When the user clicks a button on the item, it should remove the item from the view list. I'm all out of guesses as to why this is. Would it be how the data is structured? I wouldn't think so because it shows that it's being removed in the console. Anyways Thanks!
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>
EDIT
adding service how I get the items --
getItems(): Observable<any> {
return this.http.get(someEndpoint)
.map(res => res.json());
}
Try to do the following:
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();
}
This completely changes the object reference and should trigger a DOM update.
If this does not work, try to wrap your splice in a setTimeout:
setTimeout(() => { this.items.splice(i, 1); }, 0);
You can also try to inject public zone: NgZone
in the constructor and run
splice in this.zone.run(() => { this.items.splice(i, 1); });
. This is another way of forcing change detection.
EDIT:
In your getItems()
method, try to do this:
getItems() {
this.stopService.getItems().subscribe(item => {
this.items = [...item];
});
}
Plunker reference:
Plunker demonstration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With