Reputation: 25
I'm following a guide that shows how to build a to-do list app in ionic. The guide doesn't show how to remove items from the list, so I decided to try it myself. I can't for the life of me get my removeItem()
function to work. No matter which item in the list I tap the delete button on, it deletes the last item in the list. I'll include the page and template that involve the removeItem()
function. Anyone have any ideas or tips?
import { Component } from '@angular/core';
import { ModalController, NavController } from 'ionic-angular';
import { AddItemPage } from '../add-item/add-item'
import { ItemDetailPage } from '../item-detail/item-detail';
import { Data } from '../../providers/data/data';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public items = [];
constructor(public navCtrl: NavController, public modalCtrl: ModalController, public dataService: Data) {
this.dataService.getData().then((todos) => {
if(todos){
this.items = JSON.parse(todos);
}
});
}
ionViewDidLoad(){
}
addItem(){
let addModal = this.modalCtrl.create(AddItemPage);
addModal.onDidDismiss((item) => {
if(item){
this.saveItem(item);
}
});
addModal.present();
}
saveItem(item){
this.items.push(item);
this.dataService.save(this.items);
}
removeItem(item) {
//this.items.splice(item, 1);
let index = this.items.indexOf(item);
this.items.splice(index, 1);
this.dataService.save(this.items);
}
viewItem(item){
this.navCtrl.push(ItemDetailPage, {
item: item
});
}
}
<ion-header>
<ion-navbar color = "secondary">
<ion-title>
To-do List
</ion-title>
<ion-buttons end>
<button ion-button icon-only (click)="addItem()"><ion-icon name="add-circle"></ion-icon></button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let item of items" >{{item.title}}
<ion-buttons end>
<button ion-button icon-only color="danger" (click)="removeItem()"><ion-icon name="trash"></ion-icon></button>
</ion-buttons>
</ion-item>
</ion-list>
</ion-content>
Upvotes: 2
Views: 68
Reputation: 16384
In your case you need to know, which item to remove, so you can pass it as argument:
(click)="removeItem(item)"
It will get current item from *ngFor
loop and will pass as an argument.
Upvotes: 2