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

Tips for optimizing the page speed of your Pixi JS app by ensuring it runs efficiently after the page loads

On my website, I implemented a dynamic gradient animation with shape-changing blobs using pixi js. The animation functions flawlessly, but the issue arises when I run page speed tests - the test assumes that the page has not finished rendering because the ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

Having several horizontal scrollbars at once on a single webpage

I stumbled upon a great example showcasing how to scroll a div on my page: Check out this Codepen - https://codepen.io/zheisey/pen/xxGbEOx Although, I am looking to extend this functionality to allow multiple divs to scroll together. Any suggestions? I ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Having trouble with bootstrap carousel malfunctioning on Firefox browser?

I'm experiencing an issue with the carousel slider on my website. It seems to only be working in Chrome and not in Mozilla Firefox. You can view the live site at: Below is the code I have used for the carousel: <header id="myCarousel" class="car ...

Uncover the solution to eliminating webpack warnings associated with incorporating the winston logger by utilizing the ContextReplacementPlugin

When running webpack on a project that includes the winston package, several warnings are generated. This is because webpack automatically includes non-javascript files due to a lazy-loading mechanism in a dependency called logform. The issue arises when ...

Using infoWindows with multiple markers in Google Maps

i have developed a custom Google Maps application that pulls data from a CSV file. The functionality works well, but I am facing an issue with the infoWindow when looping through all the objects. It seems like the problem stems from the marker variable bei ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

The process of uploading images to a server by making an AJAX call to a PHP file

I have an input file and I want to upload the attached file to the server with a message saying "uploaded successfully" when I click on the upload button. However, I am getting a "file not sent" message. (The uploaded images need to be saved in the uploa ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

What are the steps to ensure compatibility with relative paths when transitioning from v5 to v6?

In my application, there are scenarios where multiple routes must pass through a component before rendering specifics. Additionally, there are situations where something is displayed for the parent route and then divided for the children. It's crucia ...

javascript implementing optional chaining for a single parameter

Is it possible to implement optional chaining on a single parameter? setAllProperties( Object.values(users).flatMap(({ properties }) => Object.values(properties) ) ); I am looking for a way to ensure that the properties folder exists in ...

MUI: reveal multiple selection when hovering & prevent dropdown from moving around

Utilizing material ui, I am facing two issues with a multiple select component that I cannot seem to resolve: While selecting an item, the dropdown moves around (I have already attempted solutions like MenuProps={{ variant: "menu", getContentAnc ...

The promise object is displayed instead of the actual data retrieved from the API call

I am currently working on fetching data from an API and showcasing the name of the returned data on the front end. This function successfully retrieves the data through an API call: async function retrieveData(url){ var _data; let response = await fetch( ...

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

Rendering a Vue select list before receiving data from a Meteor callback

I am currently facing an issue with populating my events array from a meteor call so that it appears in a select list. The 'get.upcoming' Meteor function returns an array of JSON objects, but it seems like the select list is being rendered before ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

The animation did not cause a transition to occur

After creating a search modal triggered by jQuery to add the class -open to the main parent div #search-box, I encountered an issue where the #search-box would fade in but the input did not transform as expected. I am currently investigating why this is ha ...