Eliminate the chosen and marked items from a list - Angular 2+/ Ionic 2

Currently, I have a checkbox list on my page. Whenever a user selects the "Save" button, the checked items should be removed from the list and moved to the saved tab that is also displayed. While I have successfully implemented the functionality for removing an item, I am looking for guidance on how to determine whether an item is checked before removing it. Any help would be greatly appreciated. Thank you!

HTML

<ion-content class="checks">

    <div [ngSwitch]="messages">

    <ion-list active *ngSwitchCase="'received'">
      <ion-item>
        <ion-label>Select All</ion-label>
        <ion-checkbox (click)="checkAll()" [(ngModel)]="selectedAll" ></ion-checkbox>
      </ion-item>


    <ion-item *ngFor="let rmessage of rmessages; index as i">
        <ion-label>{{rmessage.text}}</ion-label>
        <ion-checkbox [checked]="selectedAll" [(ngModel)]="singleChecked.checked" ></ion-checkbox>
    </ion-item>

        <button ion-button full (click)="save($index)" >Save</button>
    </ion-list>
  <ion-list radio-group *ngSwitchCase="'sent'">
    <ion-list-header>Saved Messages</ion-list-header>
        <ion-item>
        <p>Saved message here</p>
        </ion-item>
  </ion-list>
</div>
</ion-content>

TypeScript

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

import { NavController, PopoverController, ViewController, ToastController } from 'ionic-angular';


@Component({
  selector: 'page-messages',
  templateUrl: 'messages.html'
})
export class MessagesPage {
selectedAll: boolean = false;
messages: string = 'messages';
findIndex: any;
singleChecked: boolean = false;
rmessages: any[] = [
    { text: 'This is a test message.' },
    { text: 'This is a second test message.' },
    { text: 'This is a third test message.' }
  ]

  constructor(public navCtrl: NavController, public popoverCtrl: PopoverController, private toastCtrl: ToastController) { 
    this.messages = 'received';
  }

 ionViewDidLoad() {
}

checkAll(){
  console.log(this.messages.length)
  if(this.selectedAll){
    this.selectedAll = true

  }
  else {
    this.selectedAll = false
  }

}

save(index){

    this.rmessages.splice(
          this.rmessages.indexOf(index), 1)

}

}

Answer №1

To optimize your code, some changes are needed: Your rMessages model should be enhanced for better functionality

rmessages: any[] = [
    { text: 'Sample message for testing.' , selected:false},
    { text: 'Another test message.', selected:false },
    { text: 'Yet another test message.', selected:false }   ] 

Within your ngFor loop

<ion-checkbox [(ngModel)]="rmessage.selected"  ></ion-checkbox>
    </ion-item>

For the selectall feature, iterate through rmessages using foreach or similar method to modify selected to true or false

In the Save function

utilize rmessages.filter to retrieve selected items and save them in a separate tab

rmessages.filter(function (x) { return x.selected;}).map(function(y){ return y.text;});

then update rmessages by filtering out unselected items

rmessages =  rmessages.filter(function (x) { return !x.selected;}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered when sending information to web service repeatedly

After populating an array with data, the information is logged into a database using a web service when the array reaches a specific record count. However, upon calling the web service, I encountered an error related to a parameter being passed: Error Ty ...

Having trouble changing the Font Awesome icon on click?

I'm struggling to figure out why I can't change a font awesome icon using a toggle. I've tried various solutions but nothing seems to be working. Any insights on what might be causing this issue? (HTML) <span class="toggle-icon" ...

Setting session expiration for an HTML page in MVC with JavaScript - A step-by-step guide

I'm working on a HTML page within an MVC framework that includes a button click function. I'm trying to figure out how to redirect the user to the login page if the page remains idle for 30 minutes. I've attempted using the code snippet belo ...

Adding several lines of HTML content from an object using jQuery's append method

Currently, this is what I have: $(document).ready(function() { $.ajax({ type:"GET" , url:'{{url("/api/getcart")}}' , dataType:"json", success: function(data){ $('#price').append(data.cartitems[1].product.pr ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

Navigating through the features of www.addthis.com is simple and straightforward

I am looking to integrate the addthis.com plugin into my website. Specifically, I want to pass my own data to the plugin when users click on the email link. This data should then be sent to the client. Is there a way to achieve this? ...

The Tools of the Trade: TypeScript Tooling

Trying out the amazing Breeze Typescript Entity Generator tool but encountering an error consistently. Error: Experiencing difficulty in locating the default implementation of the 'modelLibrary' interface. Options include 'ko', 'b ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

Using Vue JS to handle image upload with "PROP MUTATING"

Apologies for any language barriers or inaccuracies in my English. I have a single component designed specifically for image uploads. It is currently being utilized in two forms: an add form and an edit form. In the edit modal, the Image URL is passed as ...

How to handle non-ASCII characters when encoding in JSON?

I understand that json_encode requires UTF-8 encoding, and I have already ensured that my data is encoded as such. However, when attempting to pass a PHP array to JavaScript, I am encountering difficulties in transferring the data successfully. To test th ...

Issue with Angular 8: Unable to access property 'database' of undefined when using @firebase

Recently, I decided to upgrade my configuration from angularfire2 v4 to @angular/fire v5.2.1 and firebase from v4 to v6.2.4. Unfortunately, during this process, I encountered an issue that caused the console to log the following error message: TypeError: ...

Running a script upon service initialization

Can code be run when a service is first initialized? For instance, if the product Service is being initialized, I'd like to execute the following code: this.var = this.sharedService.aVar; ...

Trapped in the Web of Facebook OAuth

I've been struggling with this issue for a day now and I can't seem to pinpoint where I'm going wrong. I have experience working with JavaScript on the client side and recently started following a book tutorial. However, it appears that Face ...

Unlocking new perspectives with a click

Currently exploring Angular development, I have encountered a question here but couldn't find the solution I was looking for. I am seeking suggestions and ideas on how to approach this issue. Essentially, my HTML includes buttons like the ones shown ...

React array mapping issue does not produce any error message

I have exhaustively searched through every answer on Stack Overflow in hopes of finding a solution to my problem. However, I find myself at an impasse as there are no error messages appearing in the console. It seems that there is a hidden bug eluding my d ...

ReactJS - What is the best way to output a string from a functional component?

Utilizing @apollo/client in my React project for handling backend APIs. Within the file appollo.js, I am attempting to make a call to the backend API link based on certain conditions. Currently, appollo.js consists solely of functions and is not considere ...

Tips for updating the color of the mat-paginator's border at the bottom

Is there a way to change the border bottom color of my mat-paginator when an option is selected? It currently defaults to purple, but I would like to customize it. Any suggestions? Click here for an example of the current purple border on Mat-paginator. ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

The reason behind the creation of .pnp.loader.mjs and .pnp.cjs files by yarn

While working on my React project with Vite, I noticed that when using yarn to start the "live server," two new files are created: .pnp.loader.mjs and .pnp.cjs. Can anyone explain what these files are for? I've never come across them before as I usual ...

Is the branch of ExtJS 4.1 TreeStore lazy loading extending?

I am working on implementing lazy loading of tree branches in an MVC application using extjs4.1. The branches are located on different URLs and I have faced several challenges along the way. Unfortunately, at this point, the branching functionality is not ...