The mat-slide-toggle component does not recognize the checked binding

My angular app contains the mat-slide-toggle functionality.

switchValue: {{ switch }} <br />
  <mat-slide-toggle [checked]="switch" (toggleChange)="toggle()">Toggle me!</mat-slide-toggle>
</div>

This is how the component looks:

  switch = false;

  toggle() {
    // backend request and heavy calculation performed here
    this.switch = false;
  }

Issue arises because the toggle does not update the switch property. Even though the user toggles the switch from off to on, the switch value remains false. Is this expected behavior?

Answer №1

If you want to change the state of a checkbox, simply pass its reference into the change method and update it accordingly!

import { Component } from '@angular/core';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { FormsModule } from '@angular/forms';

/**
 * @title Basic slide-toggles
 */
@Component({
  selector: 'slide-toggle-overview-example',
  template: `
  switchValue: {{ switch }} <br />
  <mat-slide-toggle #toggle [ngModel]="switch" (change)="toggleAction(toggle)"
    >Toggle me!</mat-slide-toggle
  >
  `,
  standalone: true,
  imports: [MatSlideToggleModule, FormsModule],
})
export class SlideToggleOverviewExample {
  switch = false;

  toggleAction(toggle: any) {
    toggle.checked = false;
  }
}

Check out the demo on Stackblitz

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

Is there a way to have my accordion adjust automatically?

I have developed a dynamic accordion component that populates its values from the parent component. However, I am facing an issue where each accordion does not respond individually to clicks. Whenever I click on any accordion, only the first one expands an ...

What is the best way to sort through data if I enter more than three characters to filter the results?

Hey there, I'm currently in the process of developing a search bar that functions by displaying only filtered last names from a table when more than 3 characters are typed. The condition for filtering is empty. Here is the HTML code: <mat-form-fi ...

The checkbox confirmation button appears to be absent in the ngx mat date time picker

I encountered a styling issue with the ngx mat datetime picker in my Angular 15 project. You can find the package here. To resolve the issue, I included @import "https://fonts.googleapis.com/icon?family=Material+Icons"; in my styles.scss file, and that re ...

Angular 2.0 encountered an unexpected value from the module 'AppModule' which appears to be an '[object Object]'

Every time I attempt to load my angular version 2.0 application, I encounter the following error: (index):21 Error: Error: Unexpected value '[object Object]' imported by the module 'AppModule' import { ModuleWithProviders } from ' ...

Is it feasible to connect to an output component without using EventEmitter?

When it comes to creating components, I've found it quite easy to use property binding for inputs with multiple options available like input(). However, when dealing with component outputs, it can be a bit complicated as there's only one option u ...

angular click triggers the following content

How can I make the following content appear when clicked? I have a list of content that displays up to 20 items, but I want to show the rest when clicked. I have created the nextMovieList method for this purpose. import { Component, OnInit } from ' ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

Include form data into an array of objects within an Angular data source

I am struggling to add the edited form data from edit-customers-dialog.ts into an array of objects in my datasource. The form.data.value is returning correctly, but I'm facing issues with inserting it properly into the array. As a beginner in Angular ...

The Angular @Input directive may be prone to receiving inaccurate model data

I am currently working on setting up @Input for my component using a model that resembles the following: interface Car { sail?: never tires: number weight: number } interface Boat { tires?: never sail: boolean weight: number } exp ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

Parsing a JSON array using Moment.js within a subscription function

I have a series of time entries within a data JSON array that I need to parse and format using Moment.js. The formatted data will then be stored in the this.appointmentTimes array for easy access on my view using {{appointmentTime.time}}. Here is the JSON ...

No output returned by SwitchMap in Angular 2

I'm facing an issue with my SwitchMap implementation and struggling to resolve it. The problem occurs when I have a collection of category buttons that, when clicked, trigger a server call to load the corresponding data. However, if I switch between t ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

Issue with offline functionality in Angular 4 project

I am currently working on an E-commerce Project utilizing Angular 4, Bootstrap, and font-awesome. Additionally, I have incorporated .scss files, angular-cli, and have custom-built a slider component. All libraries, images, and necessary files have been ins ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Delete a specific element from an array using a specified criteria

I'm attempting to remove a specific item from an array based on the selected option. To better understand, take a look at this code: component.html <fnd-extended-select label="Tipo Prodotto:" [(ngModel)]="landingType" name="tipoprodotto"> ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

Creating robust unit tests for Node.js applications with the help of redis-mock

I am facing an issue while trying to establish a connection with redis and save the data in redis using the redis-mock library in node-typescript, resulting in my test failing. Below is the code snippet for the redis connection: let client: RedisClientTyp ...