Switch Angular checkbox to display string values instead of boolean true/false

My task is to create three checkboxes in a form with values toggling between "optin" and "optout" as I check/uncheck the checkboxes. Additionally, all checkboxes should be checked by default for the "optin" value. I'm struggling to find a solution, any assistance would be greatly appreciated :( as I am new to Angular.

Below is the code snippet I am currently working on:

component.html

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">
    <div class="form-group">

   <input type="checkbox" formControlName="optOutFlag1" id="privacy" aria-labelledby="check1">
   <label for="privacy" id="check1"> Checkbox 1</label><br><br>

   <input type="checkbox" formControlName="optOutFlag2" id="security" aria-labelledby="check2">
   <label for="security" id="check2"> Checkbox 2</label><br><br>

   <input type="checkbox" formControlName="optOutFlag3" id="consent" aria-labelledby="check3">
   <label for="consent" id="check3"> Checkbox 3</label><br><br>

   <button> Submit Preference </button>

</div>
</form>

component.ts file

optOutForm:FormGroup
this.optOutForm=this.fb.group({
    optOutFlag1:["optin",Validators.required],
    optOutFlag2:["optin",Validators.required],
    optOutFlag3:["optin",Validators.required]
});  

Answer №1

When dealing with checkboxes in Angular forms, remember that the form control value is tied to the "checked" state and not the "value" attribute. It should be either true or false.

Furthermore, it's important to choose between using reactive forms or template-driven forms instead of mixing them.

Template-Driven Form

If you opt for template-driven forms, adjust your template as follows:

...
<form name="optOutForm" (ngSubmit)="onSubmit()" #f="ngForm">
   <div>
      <input type="checkbox" name="privacyOptIn" id="privacyOptIn" 
         [(ngModel)]="optIn.privacy" required>&nbsp;
      <label for="privacyOptIn">Privacy</label>
   </div>
   <div>
      <input type="checkbox" name="securityOptIn" id="securityOptIn"
         [(ngModel)]="optIn.security" required>&nbsp;
      <label for="securityOptIn">Security</label>
   </div>
   <div>
      <input type="checkbox" name="consentOptIn" id="consentOptIn"
         [(ngModel)]="optIn.consent" required>&nbsp;
      <label for="consentOptIn">Consent</label>
   </div>
   <button>Submit Preference</button>
</form>
...

In your component, ensure the model optIn has properties all set to true to have the checkboxes pre-selected.

export class MyComponent {
    optIn: {
        privacy: boolean;
        security: boolean;
        consent: boolean;
    } = {
        privacy: true,
        security: true,
        consent: true
    };

    onSubmit() {
        ...
    }
}

View Stackblitz example here.

Reactive Form

Alternatively, if you prefer reactive forms, update your template like this:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
   <div>
       <input type="checkbox" formControlName="privacyOptIn" id="privacyOptIn">&nbsp;
       <label for="privacy">Privacy</label>
   </div>
   <div>
       <input type="checkbox" formControlName="securityOptIn" id="securityOptIn">&nbsp;
       <label for="security">Security</label>
   </div>
   <div>
       <input type="checkbox" formControlName="consentOptIn" id="consentOptIn">&nbsp;
       <label for="consent">Consent</label>
   </div>
   <button>Submit Preference</button>
</form>

In your component, set up the form like this:

export class MyComponent implements OnInit {
    form: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            privacyOptIn: [true, Validators.required],
            securityOptIn: [true, Validators.required],
            consentOptIn: [true, Validators.required]
        });
    }

    // Shortcut for accessing form fields easily
    get f() { return this.form.controls; }

    onSubmit() {
        ...
    }
}

See Stackblitz example here.

UPDATE

If you want your component to emit strings 'optin' or 'optout', introduce a new variable during form submission:

export class MyComponent {
    @Output() options = new EventEmitter<{
        privacy: string;
        security: string;
        consent: string;
    }>();
    ...

    onSubmit() {
        const emittedOptions = {
            privacy: this.optIn.privacy ? 'optin' : 'optout',
            security: this.optIn.security ? 'optin' : 'optout',
            consent: this.optIn.consent ? 'optin' : 'optout',
        }
        this.options.emit(emittedOptions);
    }

Check it out in action!

Answer №2

This solution is inspired by the solution provided by Eliseo.

The checkboxes in this implementation toggle between "optin" and "optout" values when checked or unchecked. They are set to default to "optin" in the .ts file.

component.html file

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">

   <div class="form-group">

   <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag1')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag1').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="privacy">

           <label "for="privacy" id="check1">Checkbox 1</label>
  </div>

 <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag2')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag2').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="security">

           <label "for="security" id="check1">Checkbox 2</label>
  </div>

 <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag3')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag3').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="consent">

           <label "for="consent" id="check1">Checkbox 3</label>
  </div>
</div>
</form>

component.ts file

optOutForm:FormGroup

constructor(private fb:FormBuilder){}

ngOnInit(){
 this.optOutForm=this.fb.group({
    optOutFlag1:['optin',Validators.required],
    optOutFlag2:['optin',Validators.required],
    optOutFlag3:['optin',Validators.required]
   });
}

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

The check box is not visible even though it is present for selection

I'm having trouble checking a checkbox with Selenium. The webpage layout is as follows. https://i.sstatic.net/WWCGL.png When I click on 'edit,' the layout changes to this format. https://i.sstatic.net/PXYRF.png Now, I can use the xpath b ...

Creating an Image Slideshow on Your Website

I'm looking to create an image slideshow on my website that functions similarly to the one found at . However, I want the images to occupy the entire screen rather than having smaller images like the reference site. Can anyone offer guidance on how t ...

Setting up React to dynamically insert data using input fields

Recently, I've dived into the world of ReactJS. Learning it has been quite challenging for me, and I often find myself feeling demotivated while working on it. One particular issue I'm facing is trying to insert data into an h1 element using an ...

Retrieving PHP information in an ionic 3 user interface

We are experiencing a problem with displaying data in Ionic 3, as the data is being sourced from PHP REST. Here is my Angular code for retrieving the data: this.auth.displayinformation(this.customer_info.cid).subscribe(takecusinfo => { if(takecusi ...

Using jQuery to fetch and display content only when the user hovers over

Looking to optimize page loading speed by minimizing the loading time of social icons such as Facebook Like and Twitter follow buttons. Considering displaying a static image of the like buttons initially, with the actual buttons appearing on mouse hover. ...

What is the best method to "deactivate" a radio button while ensuring that a screen reader can still read the text and notify the user that it is inactive?

My current situation involves needing to deactivate certain radio buttons, while still having the option to reactivate them later. When I use the disabled attribute, screen readers will overlook this field and miss key information. I am seeking an accessi ...

How to retrieve an image from an external source using jQuery

There's a link that looks like this: http://vignette4.wikia.nocookie.net/2007scape/images/c/c1/3rd_age_amulet.png/revision/latest?cb=20141217224859 and I'm trying to figure out how to download it into a specific folder with a specific name usin ...

outside vue component access method is not recommended

I am a newcomer to Vue.js and have implemented a comment feature similar to the one described here. However, due to certain constraints, I had to make adjustments. I used a Vue component but encountered an issue where it couldn't access a method insid ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Is it possible for the *ngIf directive to stop unauthorized users from accessing my admin page through their browsers?

When the *ngIf directive is set to false, a certain element or component will not be included in the DOM. For example, let's say there is a component that displays admin tools and should only be accessible to authorized users (administrators). Will se ...

troubles with dividing string

Recently delving into JavaScript/Angular development and encountering a little roadblock. I am attempting to break up a string of a textarea into an array at the \n character within a controller by utilizing $scope.mytext.split("\n"), however, I ...

Tips for individually assigning Fastify decorators within various plugins?

I'm encountering issues with typing decorators in two separate plugins (scopes): import Fastify, { FastifyInstance } from 'fastify' const fastify = Fastify() // scope A fastify.register((instance) => { instance.decorate('utilA&apo ...

What is the method for adding <option> tags to a <select> statement using a for loop?

Currently, I am facing a challenge in dynamically populating the <option> tags within a <select> menu. My approach involves using a for loop in JavaScript to cycle through the number of options and append them to the select tag. The part of th ...

tips for updating the input format of your ngx-datepicker

My goal is to receive a date input in the format yyyy-mm-dd, however, even after selecting the date correctly, I am receiving it in the 2019-07-08T12:16:10.000Z format. <input class="form-control" style="width: 48%;display: ...

A guide to using the up and down keys to switch focus between div elements in a react component with TypeScript and CSS

I am currently working with a scenario where data is being displayed within different div elements, and I wish to enable the selection/focus of a specific div when users use the up/down arrow keys. While trying to achieve this functionality by using refs ...

ajax-jquery request declined

I have a jquery-ajax function that is being called multiple times with different IP addresses each time. This function makes a call to an action in the mvc4 controller responsible for executing a ping and returning the results. After analyzing the request ...

Receiving an eslint error while trying to integrate Stripe pricing table into a React web application

If you're looking to incorporate a Stripe documentation code snippet for adding a stripe-pricing-table element, here's what they suggest: import * as React from 'react'; // If you're using TypeScript, don't forget to include ...

A step-by-step guide on integrating a Django template tag and HTML element into an HTML page using Javascript

Is there a safe way to insert HTML that includes Django template tags using JavaScript in my project? For instance, if my template contains the following code: <div id="some-element"> <span id="my-tag">{{ my_data }}</sp ...

Tips for resolving a double click issue with a jQuery slide up/down animation

When I click a button, there is an animation that makes a div slide up and then down again. It functions the way I want it to, but the first time you click it, it doesn't work; you have to click twice for it to respond. Someone recommended using... ...

Leverage nan for the transmission and retrieval of Float32Array within an addon module

I am currently attempting to utilize nan in order to perform calculations on an array of floating point numbers within an add-on and then return the result as a Float32Array. However, while the arguments have IsNumber() and NumberValue() functions, there ...