Tips for obtaining the ID and value for every Slide-Toggle element

I recently posed a question that was somewhat similar to this, but I am facing a slightly different issue now. Within a table column, there are Slide-Toggle elements that users can toggle between true and false an unlimited number of times. Following these toggles is a button that allows the user to submit all the true/false values. In my HTML, these Slide-Toggle elements are generated from a notifications array using a for loop. What would be the most efficient and effective way to retrieve the true/false values of all these slide-toggles along with their IDs? Since I intend to submit them, it is crucial for me to achieve this. Below is what I have attempted so far

HTML

<h3>Notifications</h3>
    <table class="table" id="thetable">
            <thead>
              <tr>
                <th scope="col">#</th>
                <th scope="col">Tasks</th>
                <th scope="col">IsFinished</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let not of notifications;" 
              [ngStyle]="{ 'background-color': (not.isFinished ? '#dddddd' : 'white') }"
              >
                 <th scope="row">{{not.id+1}}</th>
                  <td>{{not.task}}</td>
                <td>
                        <section class="example-section">
                                <mat-slide-toggle
                                    [id]="not.id"
                                    class="example-margin"
                                    [color]="color"
                                    [checked]="not.isFinished"
                                    [disabled]="not.isFinished"
                                    (change)="onChange($event)"
                                    >
                                </mat-slide-toggle>
                              </section>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="row">
                <div class="col">
                <button mat-raised-button color="primary" (click)="openDialog()">Add Task</button>
                <button mat-raised-button color="primary" (click)="onSave()">Save</button>
            </div>

TypeScirpt (Initialization of Array)

 ngOnInit() {
    this.notifications=this.notificationService.getNotifications();
  }

Answer №1

Connect toggle with ngModel in the following way:

<mat-slide-toggle [id]="not.id" class="example-margin" [color]="color"
 [checked]="not.isFinished" [(ngModel)]="not.isFinished"[disabled]="not.isFinished" (change)="onChange($event)" >
 </mat-slide-toggle>

Next, in your save method:

 onSave(){
      this.notifications.forEach((n)=>{
      console.log(n.id) //this is the id of your toggle
      console.log(n.isFinished)//this is the value of the toggle
      })
    }

UPDATE

If you prefer not to use ngModel, you can check if your toggle element has the mat-checked class. Angular Material adds the checked class when the toggle is active. Update your method as follows:

 onSave(){
          this.notifications.forEach((n)=>{
          console.log(n.id) //this is the id of your toggle
           var ele=document.getElementById(n.id)
           console.log(ele.classList.contains('mat-checked'))//this is the value 
         of the toggle
          })
        }

Answer №2

To access the ID of the toggled element when it changes, include not in the parameter of the (change)="onChange(not)" function. This will help you keep track of the changed IDs and allow you to store them in a separate array for future reference.

When saving data:

onSave(){
  this.completedTasks = this.tasks.filter((t) => {
    return t.id && t.isCompleted; // filters and returns tasks that are completed
  })
}

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

Cannot adjust the chosen rage within the Material Date-Rangepicker

I'm trying to customize the colors of a material date range picker, but I can't seem to find the right class for the selected range. https://i.sstatic.net/P4Rys.png So far, I've managed to change the color of the selected range using the f ...

Tips for adding line breaks in TypeScript

I'm brand new to angular and I've been working on a random quote generator. After following a tutorial, everything seemed to be going smoothly until I wanted to add a line break between the quote and the author. Here's what I currently have ...

Leveraging a Static HTML landing page template within an Angular 6 application

I currently have an Angular 6 app hosted on example.com, with the dist folder being served on port 5000. Additionally, I have a separate landing page folder with its HTML, CSS, and JS files being served on port 6000 at example.com/welcome. Is there a way ...

Utilizing JSON Data with JQuery: A Beginner's Guide

I am using a setTimeout function to reload another function every 5 seconds. The update_list function is responsible for rendering entrances in a view. However, when there are many entrances and you have scrolled down, the list empties and reloads every e ...

How can I show the MySQL "result" object to the user using express-handlebars?

In my Node.js code, I currently have a query that looks like this: app.get('/fav/books', function(req, res){ var sql = ("SELECT title, pictureUrl, author, description, genre FROM books") connection.query(sql, function(err, result){ if(err) ...

Error encountered at line 51, column 7 in the script (vm.js) while executing JavaScript code for a Discord bot

When I run node index.js, I encounter an error. Here is the code: const botconfig = require("./botconfig.json"); const Discord = require("discord.js"); const bot = new Discord.Client({disableEveryone: true}); bot.on("ready", async () => { console.log ...

After implementing the msw-storybook-addon, I encountered an error stating "Unexpected character '#' in node_modules/../Emitter.js."

Seeking to utilize mock servers for my stories, I encountered an error while setting up the Storybook with msw-storybook-addon. After following the steps outlined in both this and this resources (which have different instructions for preview.js), running t ...

Modify the color of the components in Select from Material-UI

After reviewing numerous questions and answers on this topic, I have yet to find a suitable solution for my issue. Seeking guidance from the community for assistance. Utilizing the Select component from @mui/material to showcase the number of records per ...

What is the reason for XMLHttpRequest overwriting preexisting events?

After clicking a button, I trigger an XMLHttpRequest event. However, I noticed that the original event becomes null once the request is sent. Why does this occur? Is there a way to maintain the original event? document.getElementById('start') ...

Discover the subsite inventory of a SharePoint site using TypeScript

Is there a way to gather all sub-sites from my SharePoint site and organize them into a list? I initially thought of using this.context.pageContext, but could not locate it. Please excuse my seemingly simple question, as I am still learning TypeScript. ...

Executing a component's method using HTML in Vue2

In my development project, there is a .vue file named ServiceList. This file imports the component called Information.vue. My objective is to execute the code from the Information component in a loop within the template of the ServiceList file. Here is an ...

Error in Typescript: TypeError is not defined

I am still getting the hang of TypeScript and React. Lately, I've been working on integrating the react-rewards npm library into my project but I'm facing one unresolved issue. type Props = {} class Surprisebutton extends Component<Props> ...

Bootstrap is causing issues with unidentified div elements

I recently embarked on creating a slideshow using HTML, CSS, and jQuery. After completing the slideshow, I decided to add an interactive page beneath it. To streamline the layout process, I opted to utilize Bootstrap. However, upon loading Bootstrap, I en ...

Hide the MaterialTopTabNavigator from view

Is there a way to hide the react native MaterialTopTabNavigator on the screen while still maintaining the swiping functionality between screens? I want the user to be able to swipe between screens but not see the tab navigator itself. const Tab = creat ...

Retrieve Next Element with XPath

I recently started working with XPATH and have a few questions about its capabilities and whether it can achieve what I need. The XML Document structure I am dealing with is as follows: <root> <top id="1"> <item id="1"> < ...

At initial glance on iOS, the login page remains hidden, but as I tilt the phone, the page fields slowly start to appear

Encountering a strange issue when accessing my application on iOS 11. Initially, the page fails to load completely with missing background and field labels. However, I am able to click on objects. Oddly enough, if I tilt my iPhone or zoom in, the page load ...

What is the reason for initializing I with the length of the response?

I am attempting to generate a table using an AJAX JSON response, but the for loop sets i to the maximum value right away. $.ajax(settings).done(function (response) { console.log(response); var i = ""; td = document.createElement('td'); t ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

Getting response headers in Angular by utilizing an HTTP interceptor

Seeking guidance on how to interpret response headers when utilizing httpinteceptor in Angular. I have exposed all the tokens in my Node.js application, but am facing challenges in comprehending all the keys passed in the response headers. intercept(req: ...

Exploration of continuations within V8 or a different C++ JavaScript engine

Are there any options for implementing continuations in V8? If not, are there other JavaScript engines for C++ that offer this capability? I am interested in creating an application that requires a JavaScript interpreter with support for continuations, si ...