Modify the value of mat-slide-toggle from TypeScript code

This is the HTML code I have for a mat-slide-toggle element, with a toggleStatus() function:

<span class="form-control form-control-plaintext">
              <mat-slide-toggle name="status" checked=""
                              formControlName="status" #status>
              <label *ngIf="!formGroup.get('status').value" (click)="toggleStatus(status)" style="margin: 0">Status: Disabled</label>
              <label *ngIf="formGroup.get('status').value" (click)="toggleStatus(status)" style="margin: 0">Status: Active</label>
            </mat-slide-toggle>
</span>

The toggleStatus() function simply toggles the status of the visual checkbox. However, it does not change the form control value when clicking on the label.

So, how can I make the form control value update when I click on the label?

Answer №1

To modify the value of a form control, simply access it through the form control itself,

  public updateControlValue(): void {
    const control = this.formGroup.get("status");
    control.setValue(!control.value);
  }

If you are using a reactive style form, there is no need for a separate toggle method. The value will automatically change when the user interacts with the control. Check out this stackblitz example (Open the console and interact with the button or slide toggle).

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

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

What is the reason that (click) does not send my data within <button>, while (change) within <input> does in Angular and HTML?

I am facing an issue while trying to send data to my Glassfish RESTful server. The method is activated successfully when I use (change) inside the input tag, but it doesn't work when I try using (click) or (change) to activate the method. I attempted ...

The speed of Mean Stack API calls leaves much to be desired

Our team has developed a MEAN stack application that functions smoothly on the client side. However, we have been facing issues with slow API requests and responses on the server side. For example, when a request is sent from Angular, it takes an average ...

Importing TypeScript Modules from a Custom Path without Using Relative Paths

If we consider the following directory structure: - functions - functionOne - tsconfig.json - index.ts - package.json - node_modules - layers - layerOne - tsonfig.json - index.ts - index.js (compiled index.ts ...

Issue with TypeScript problemMatcher "$tsc-watch" not actively monitoring files in VSCode

I'm attempting to avoid the necessity of using watch: true in my tsconfig.json setup. Despite utilizing VSCode's tasks with the default problem matcher $tsc-watch, I am encountering an issue where tsc is not running in watch mode during the buil ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Filtering tables in Angular 6 using checkbox options

I have a functional code snippet that filters a table using checkboxes. However, I am facing an issue when unchecking a checkbox. It does not return the original array as expected. .html <ng-container *ngFor="let group of groups"> <label cla ...

Learning how to effectively incorporate the spread operator with TypeScript's utility type `Parameters` is a valuable skill to

I have implemented a higher order function that caches the result of a function when it is called with the same parameters. This functionality makes use of the Parameters utility type to create a function with identical signature that passes arguments to t ...

The data type 'string' cannot be assigned to the type 'SystemStyleObject | undefined' in the context of Next.js and Chakra UI

I am currently working on a project that involves Next.js, TypeScript, and Chakra UI. While configuring Button themes in the button.ts file, I encountered an error related to the baseStyle object for properties like borderRadius, color, and border: Type & ...

Resolving "SyntaxError: Unexpected identifier" when using Enzyme with configurations in jest.setup.js

I'm currently facing an issue while trying to create tests in Typescript using Jest and Enzyme. The problem arises with a SyntaxError being thrown: FAIL src/_components/Button/__tests__/Button.spec.tsx ● Test suite failed to run /Users/mika ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

Creating a fresh type in Typescript based on object keys that are already defined within an interface

Here is the scenario I am currently dealing with: interface ListField { code: number; message: string; } interface List { [key: string]: ListField; } export const allCodes: List = { FIRST: { code: 1, message: 'message 1', }, ...

Verifying data types on combined function parameters

In the process of creating a function called getLocale(obj, key, locale), I aim to retrieve a specific locale from an object based on a given key. If the desired locale variant is not available, it should return a fallback option. While adding type checki ...

What could be causing the lack of Tailwind CSS intellisense in a Next.js app with TypeScript?

Check out my tailwind.config.ts file I've been trying to figure it out by watching YouTube tutorials, but nothing seems to be working. Even with the tailwind.config.ts file in my Next.js app, it still isn't functioning properly. Perhaps there&ap ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Encountering an issue in a Next.js application while building it, where an error is triggered because the property 'protocol' of 'window.location' cannot be destructured due to being undefined

While building my nextjs application, I encountered the following error. My setup uses typescript for building purposes, although I am only using JavaScript. Build error occurred: TypeError: Cannot destructure property 'protocol' of 'window ...

Refresh the child component whenever there is a change in the parent's state

As of now, I am in the process of developing a MultiCheckbox Component which looks like this: Checkbox.tsx import './Checkbox.scss'; import React, {ChangeEvent, Component} from 'react'; /* * Description of Checkbox properties */ in ...

When working with Angular and NGRX, I often wonder if opening my app in multiple tabs within the same browser will result in all tabs pointing to a single NGRX instance

Is it possible to access my localhost:9000 in multiple tabs? If I open it in 3 tabs, will all those 3 tabs point to a single NGRX instance or will each tab of localhost have its dedicated NGRX instance? I haven't had the chance to test this yet. ...

The error message "TypeScript is showing 'yield not assignable' error when using Apollo GraphQL with node-fetch

Currently, I am in the process of implementing schema stitching within a NodeJS/Apollo/GraphQL project that I am actively developing. The implementation is done using TypeScript. The code snippet is as follows: import { makeRemoteExecutableSchema, ...