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

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Launching an Ionic 2 stack app on Heroku is a smooth process

I am currently facing a challenge with deploying my Ionic App. The app's server is deployed on Heroku, but I want to deploy the entire app. However, every tutorial I have come across seems to result in various errors. Here is how my folder structure ...

Sending information to the styles feature in Angular 2

Is there a way to transfer data from an Angular tag to the styles in the @Component? Take a look at my component: import { Component, Input } from '@angular/core'; @Component({ selector: 'icon', template: `<svg class="icon"> ...

How can we simultaneously execute multiple HTTP requests in Angular 6 by leveraging the power of forkJoin and ngrx?

Current Situation In the realm of my angular6 application, I find myself juggling three distinct categories: catA, catB, and catC. Each of these categories requires data retrieval from 3 separate APIs. Upon selecting any category, the CategoryDetailsCompo ...

Tips for incorporating Material UI Icon v1.0.0-beta.36 into a .tsx component

Currently utilizing material-ui-icons v1.0.0-beta.36. I am endeavoring to incorporate a Search icon within a .tsx component. .tsx component: import React, { Component, ReactElement } from 'react' import Search from 'material-ui-icons/Sear ...

Is it possible to easily organize a TypeScript dictionary in a straightforward manner?

My typescript dictionary is filled with code. var dictionaryOfScores: {[id: string]: number } = {}; Now that it's populated, I want to sort it based on the value (number). Since the dictionary could be quite large, I'm looking for an in-place ...

Sending information from a component to a route in Angular2

Is it possible to transfer data from one component to another without displaying it in the URL during routing? Currently, I am passing data using route parameters like this: { path: 'edit-tags/:type/:name/:id', component: EditTagsCompon ...

Tips on providing validation for either " _ " or " . " (select one) in an Angular application

I need to verify the username based on the following criteria: Only accept alphanumeric characters Allow either "_" or "." (but not both) This is the code snippet I am currently using: <input type="text" class="form-control" [ ...

What is the process for dynamically loading a component by its name in Angular 2?

I am currently incorporating dynamic loading of angular components in my application by using the following code snippet. export class WizardTabContentContainer { @ViewChild('target', { read: ViewContainerRef }) target: any; @Input() TabCont ...

Angular2: Retrieving the XLS file received from the backend

I am utilizing Laravel 5.1 REST API along with the maatwebsite solution to create an Excel file from the back-end. My main goal is to initiate the download of the file upon button click. Currently, I am making an AJAX request through Angular2's Http s ...

Angular2 - Access to fetch at 'https://example.com' from

Requesting some guidance on integrating the forecast API into my angular2 application. Currently facing a Cross-Origin Error while attempting to access the API. Any suggestions on resolving this issue? search(latitude: any, longitude: any){ consol ...

Guide on creating a Jasmine test for a printer utility

Currently, I am working on writing a Jasmine test for the print function shown below: printContent( contentName: string ) { this._console.Information( `${this.codeName}.printContent: ${contentName}`) let printContents = document.getElementById( c ...

What is the mechanism for invoking functions defined with the arrow syntax in Angular?

Referencing this code snippet from the tutorial at https://angular.io/tutorial/toh-pt4, specifically within the hero.component.ts file: getHeroes(): void { this.heroService.getHeroes() .subscribe(heroes => this.heroes = heroes); } After analyz ...

Learn How to Implement Styling in Material UI using Styled Components

Utilizing styled-components with MaterialUI integration. Encountering the following error in LoginTextField component and seeking a resolution. Error Message: [ts] Type '{ width: number; }' is missing the following properties from type &apos ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

What steps can I take to resolve a CSS problem in an Angular Web Component within a React Application?

I recently integrated an Angular Web Component with some widgets from Angular Material UI into my simple React Application. While the functionality of the buttons, tables, and radio buttons is working perfectly fine, I am facing issues with the styling and ...

When attempting to redirect to the home page in Angular 6, the page successfully redirects but fails to load properly

I am new to using angular. Recently, I converted a large project from html/css/php/js to twig/slim, and switched the hosting platform from apache2/sql to s3 buckets/lambda apis. While I have successfully converted smaller projects to angular without any i ...

Make sure to incorporate the .gitignored files that are compiled from typescript when running the `npm install -g

Looking for a way to ignore the JavaScript files compiled from TypeScript in my git repository to make merging, rebasing, and partial commits easier. Here's how I have it set up: tsconfig.json { "compilerOptions": { "outDir": "./dist" ...

What is the best way to adjust the Material Drawer width in Reactjs to match the width of its children?

Currently, I am utilizing the Material-ui Drawer component to toggle the display of content on the right side of the screen. The functionality I am aiming for is that when the Drawer opens, it will shrink the existing content on the right without any overl ...