Switching the Checkbox Data Binding Feature in Angular

I am looking to send a value based on a toggle switch checkbox selection between Hourly or Salary. How can I incorporate this into the form below?

html

<div class="row">
    <div class="col-sm-6">
        <div class="can-toggle">
            <input id="a" type="checkbox">
            <label for="a">
                <div class="can-toggle__switch" data-checked="Salary" formControlName="payType" data-unchecked="Hourly"></div>
            </label>
        </div>

    </div>
</div>

TypeScript:

 payType = new FormControl(true, [Validators.required]);
model.payType = createForm.payType;

Answer №1

Feel free to give the following code a try as it should meet your needs.

Your HTML Component

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
    <div class="row">
      <div class="col-sm-6">
        <div class="can-toggle">
          <input id="a" type="checkbox" formControlName="payType" />
          <label for="a">
            <div class="can-toggle__switch">{{myForm.controls['payType'].value ? "Fixed" : "Variable"}}</div>
          </label>
        </div>
      </div>
    </div>
    <div class="row">
      <button type="submit">Submit</button>
    </div>
  </form>

Your TypeScript Component

myForm: FormGroup;
constructor() { }

ngOnInit(): void {
    this.myForm = new FormGroup({
      payType: new FormControl(false)
    })
}

onSubmit(){

}

Answer №2

Customizing the default value for a checkbox may be necessary in some cases. You have the option to create your own checkbox logic that defines values for both the checked and unchecked states.

To learn more, refer to the Angular documentation on ControlValueAccessor.

An example implementation can be found on StackBlitz.

app.component.ts

import { Component, OnInit } from "@angular/core";
import { FormControl, Validators } from "@angular/forms";

@Component({
  selector: "my-app",
  template: `
    <app-custom-checkbox
      [checkedValue]="checked"
      [unCheckedValue]="unChecked"
      [formControl]="formControl"
    >
      {{ checked }}/{{ unChecked }}
    </app-custom-checkbox>
  `,
  styles: [""]
})
export class AppComponent implements OnInit {
  readonly checked = "Salary";
  readonly unChecked = "Hourly";

  formControl = new FormControl(this.unChecked, Validators.required);

  ngOnInit() {
    this.formControl.valueChanges.subscribe(console.log);
  }
}

custom-checkbox.component.ts

import { Component, forwardRef, Input, OnInit } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";

export const CHECKBOX_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => CustomCheckboxComponent),
  multi: true
};

@Component({
  selector: "app-custom-checkbox",
  template: `
    <label>
      <input
        type="checkbox"
        [checked]="checkedValue === value"
        (change)="onChanged($event)"
        [disabled]="disabled"
      />
      <ng-content></ng-content>
    </label>
  `,
  styles: [""],
  providers: [CHECKBOX_VALUE_ACCESSOR]
})
export class CustomCheckboxComponent implements OnInit, ControlValueAccessor {
  @Input()
  checkedValue: string = "true";

  @Input()
  unCheckedValue: string = "false";

  value: string = this.unCheckedValue;

  onChange = (_: any) => {};
  onTouched = () => {};
  disabled = false;

  constructor() {}

  ngOnInit() {}

  onChanged(event) {
    const isChecked = event && event.target && event.target.checked;

    this.onChange(isChecked ? this.checkedValue : this.unCheckedValue);
  }

  writeValue(value: any): void {
    this.value = value;
  }

  registerOnChange(fn: (_: any) => {}): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: () => {}): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}

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

International replacement of external interface exportation

Currently, I am utilizing the @react-native-firebase/messaging library and invoking the method messaging().onNotificationOpenedApp(remoteMessage => ....) I am aiming to replace the property data within the type of remoteMessage in order to benefit from ...

Custom Angular 2 decorator designed for post-RC4 versions triggers the 'Multiple Components' exception

Currently, I am in the process of updating my Ionic 2 component known as ionic2-autocomplete. This component was initially created for RC.4 and earlier iterations, and now I am working on migrating it to Angular 2 final. One key aspect of the original des ...

After the transition from Angular 8 to Angular 9, an issue arose with the node_modules/@zerohouse/router-tab/zerohouse-router-tab.d.ts file, as it was not declared

Error Image package.json { "name": "client", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "serveapp": "ng serve ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

The NGINX reverse proxy fails to forward requests to an Express application

I am currently in the process of setting up a dedicated API backend for a website that operates on /mypath, but I am encountering issues with NGINX not properly proxying requests. Below is the nginx configuration located within the sites-enabled directory ...

When utilizing destructuring in React.js with TypeScript, incorrect prop values are not being alerted as expected

I recently started using TypeScript and I have been enjoying it so far. However, I came across an issue today that I couldn't solve. Imagine a scenario where a parent component A passes a function that expects a numeric value to the child component B ...

Creating multiple-to-multiple relationships in Express: A beginner's guide

In developing a small API with Express and TypeScript, I am faced with handling both POST and GET requests. The POST request involves receiving a list of organizations, which may have daughter organizations that can also have their own daughters, creating ...

Failure of Styling Inheritance in Angular 2 Child Components from Parent Components

My Parent Component utilizes a Child Component. I have defined the necessary styles in the Parent CSS file, and these styles change appropriately when hovering over the div. However, the Child Component does not inherit the styling classes of the Parent Co ...

Toggle the disable state of a button depending on a specific condition

I have a scenario where I am fetching data from a server, and I need to apply a filter to a specific column. The requirement is that if the "bought" column (boolean) has a value of true, then the edit button should be disabled; otherwise, it should be enab ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...

Guide to implementing user authentication in .NET Core 2.1 Angular application

As I navigate through Visual Studio 2017, I find that the Individual User Account option is disabled in the Angular template. This leaves me wondering how to implement user authentication without this feature. Being new to VS 2017 and .Net Core 2.1, I sear ...

Transforming API data into a particular type using Typescript

I am looking to extract only specific properties from a given object. Can TypeScript interfaces be used to iterate through the data and eliminate unnecessary properties? Sample data: [ 0: { "original_language" : "en", "t ...

Is it possible to utilize a JSON file as a JavaScript object without directly importing it into the webpack compiled code?

While initiating the bootstrap process for my Angular hybrid app (which combines Angular 7 and AngularJS), I am aiming to utilize a separate config JSON file by storing it as a window variable. Currently, I have the following setup: setAngularLib(AngularJ ...

Can you explain what happens to "npm install" and "npm update" when modifications are made to package.json?

I'm struggling to understand why running the command "npm update" isn't updating my angular-cli to version 7.3.0, but when I use "npm install," it does update it to 7.3.0. Check out the macOS terminal screenshot below showing the upgrade from an ...

Implementing Default Language in Next.js 14 for Static Export without URL Prefix: A Step-by-Step Guide

Currently, I am in the process of developing a website using Next.js 14, with the intention of exporting it as a static site for distribution through a CDN (Cloudflare Pages). The website I am working on requires support for internationalization (i18n) to ...

What exactly do Dependencies mean in Angular?

As a beginner in Angular, the concept of dependencies has come up several times during my learning process. Despite my efforts to search for a clear definition of Dependencies in Angular on Google, I have been unsuccessful. Could someone please provide a ...

Enabling the "allowUnreachableCode" Compiler Option in Visual Studio 2015 Triggers "JsErrorScriptException (0x3001)" Issue

We've implemented TypeScript in our Visual Studio 2015 (Update 2) setup for a non-ASP.Net project consisting of pure HTML and JavaScript. In order to disable the 'allowUnreachableCode' option, we made adjustments in the tsconfig file. It&apo ...

Activating functions based on radio button selection in React with TypeScript

Below are the radio buttons with their respective functions: <div className="row"> <div className="col-md-4"> <label className="radio"> <input onChange={() => {serviceCalc()}} ty ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...