Remove selected items from a list

Hello all,

I have an itemlist where I can add items and stripe items when done. Now I want to delete all items that are striped but what I use in my script does not work. I know that I miss something but what? :slight_smile:

It is the part with removePost(selected)

page.ts

@IonicPage()
@Component({
  selector: 'page-boodschappenlijst',
  templateUrl: 'boodschappenlijst.html',
})
export class BoodschappenlijstPage {
	loader: Loading;
	todos: Todo[];

  constructor(
	public navCtrl: NavController,
	public navParams: NavParams,
	private todoService: TodoService,
	private alertCtrl: AlertController,
	private toastCtrl: ToastController,
	public loadingCtrl: LoadingController){
  }

  ngOnInit() {
    this.initLoader();
    this.loadTodos();
  }

  showInputAlert() {
    let prompt = this.alertCtrl.create({
      title: 'Add New Item',
      message: "Add a new item to the todo list.",
      inputs: [{ name: 'title', placeholder: 'e.g Buy groceries' }],
      buttons: [
        { text: 'Cancel' },
        {
          text: 'Add',
          handler: data => {
            this.todoService.add(data.title, []).subscribe(
              response => {
                let todo: Todo = {
                  name: data.title,
                  done: false,
                  tags: []
                };
                this.todos.unshift(todo)
              }
            );
          }
        }
      ]
    });
    prompt.present();
  }

  updateItemState(evt:any, todo: Todo) {
    if (evt) {
      let index: number = this.todos.indexOf(todo);

      if (~index) {
        if (todo.done == true) {
          todo = this.todos[index]
          this.todos.splice(index, 1);
          this.todos.push(todo)
        }
        this.todoService.saveAll(this.todos).subscribe(
          done => {
            this.presentToast(
              "Item marked as " + (todo.done ? "completed" : "not completed")
            )
          }
        );
      }
    }
  }
	
	removePost(selected){
    let index: number = this.todos.indexOf(todo);
    if(index > -1){
		this.todos.splice(index, 1);
    }
}

  private presentToast(message: string) {
    this.toastCtrl.create({message: message, duration: 2000}).present();
  }

  private initLoader() {
    this.loader = this.loadingCtrl.create({
      content: "Loading items..."
    });
  }

  private loadTodos() {
    this.loader.present().then(() => {
      this.todoService.fetch().subscribe(
        data => {
          this.todos = data;
          this.loader.dismiss();
        }
      );
    })
  }
}

page.html

<ion-content padding>
	
<ion-grid>
    <ion-row>
      <ion-col class="readjust">
        No item has been added. Use the "+" button below to add a new item.
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-content>

<ion-content padding [hidden]="!todos || todos.length <= 0">
  <ion-item *ngFor="let todo of todos">
    <ion-label [ngClass]="{stricken:todo.done}">{{ todo.name }}</ion-label>
    <ion-checkbox color="dark" [(ngModel)]="todo.done" (click)="updateItemState($event, todo)"></ion-checkbox>
  </ion-item>
</ion-content>

<ion-fab right bottom>
  <button ion-fab color="primary" (click)="showInputAlert()"><ion-icon name="add"></ion-icon></button>
</ion-fab>
<ion-fab left bottom>
<button danger (click)="removePost(selected)"><ion-icon name="delete"></ion-icon></button>
</ion-fab>

maybe a copy/paste mistake, todo doesn’t exist in your removePost. I guess it should be replaced by selected (?)

removePost(selected){
    let index: number = this.todos.indexOf(todo); // <-- todo?
    if(index > -1){
        this.todos.splice(index, 1);
    }
}

I first did that but then nothing happens. I now set it back to selected but then there is no error and nothing get deleted.

umm, ok so I think the first problem is that selected is nothing, don’t saw in your code where it’s initialized and set

then selected is an object? that’s maybe the problem, not sure that indexOf works on object but only on primitive type

https://blog.pusher.com/create-to-do-ios-android-app-ionic-angular/

This is the tutorial i followed. I have to do more than I thought to create the delete button. I go to try understand how :slight_smile:

When I use this:

public clear(): void {
this.todos = [];
}

And the button in the html is this:

<button (click)=“clear()”>

The list is cleared, but when refreshing then all items are back. This is because of local storage so I now know that there has more to be done. Also all items are deleted and not only the selected items.

this.todos = []; this set a new array to todos so yes this will clear up the all array

when you refresh your page ngOnInit is called I guess so this.loadTodos(); so all todos are loaded again. If you want to implement a clear in your service too, you have to do/call something in your this.todoService provider

about deleting one element, see my answer above it will gives you a hint, using indexes number is probably the easiest way, how to delete but it depends on the flow of your screen

Thanks, I go puzzle with it :slight_smile:

1 Like