Update the registerForm input from a boolean value to a number

Confused about how to convert a boolean to a number

Issue :

I'm struggling trying to convert my registerForm.value.aleas, which is a checkbox, into a number (0 for false, 1 for true) in order to perform a POST request (the API expects values of either 1 or 0). However, I'm having difficulty achieving this as registerForm.value always returns the default value (false if the checkbox isn't clicked and true if it is).

Attempts Made :

I attempted using ? 1 : 0, but I don't think registerForm accepts it and I haven't found another solution yet.

Sample Code :

app.component.ts

postParams(){
const token = JSON.parse(window.localStorage.getItem('token'));
const aleas = this.registerForm.value.aleas? 1 : 0;
return this.httpClient.post(`this.url?token=`,
{
token: token.token,
is_alea_chantier: aleas,

})
.subscribe(
data => {
console.log("POST PARAMS DONE",data)
},
error => {
console.log("POST PARAMS FAILED", error)
}

)
}


get f() {
return this.registerForm.controls;
}

onSubmit{
this.submitted = true;
console.log(this.registerForm.value.title)
//stop here if form is invalid
if (this.registerForm.invalid){
console.log("INVALID FORM")
return;
} else {
console.log("VALID FORM")
this.postParams();
}
}

app.component.html

<div class="container">
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()" >
<input formControlName="aleas" type="checkbox" class="custom-control-input" id="customCheck" 
name="example1">
</form>
</div>

If you have any suggestions or guidance on how to solve this issue, please let me know. Your time is greatly appreciated!

EDIT

All the responses provided were helpful, but it appears there may be a backend issue now. Thank you!

Answer №1

Ensure you are using the proper syntax to retrieve the value from the form-control:

let aleasValue = this.formControl.get('aleas').value ? 1 : 0;

Answer №2

There are various ways to convert your boolean value to a number, which can be implemented successfully both at compile time and during runtime. However, it is crucial to ensure that you are accessing the formControl's value correctly beforehand.

const optionOne = this.registerForm.get("option").value ? 1 : 0; // preferred approach
const optionTwo = Number(this.registerForm.get("option").value);
const optionThree = +this.registerForm.get("option").value; // utilizing unary operator

Answer №3

Even if you don't have a control, you can still utilize ngModel within the formControl

<div class="container">
  <form [formGroup]="registerForm" (ngSubmit)="onSubmit()" >
    <input type="checkbox" class="custom-control-input" id="customCheck" 
    name="example1" 
       [ngModelOptions]="{standalone:true}"
       [ngModel]="registerForm.get('aleas').value==1" 
       (ngModelChange)="registerForm.get('aleas').setValue($event?1:0)">
  </form>
</div>

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

Minimize the amount of information retrieved and shown based on the timestamp

I am currently working on storing and retrieving the date of a user request. For creating the timestamp, I use this code: const date = firebase.firestore.FieldValue.serverTimestamp(); This is how I fetch and display the data: <tr class="tr-content" ...

When attempting to pass an array of objects to a child component, TypeScript raises an error regarding types

Hey everyone, I'm currently facing an issue while trying to pass an array of objects as props. Here's the content of my data.json file: [ { "category": "Reaction", "score": 80, "icon": " ...

Tips for utilizing favicons-webpack-plugin in Angular 8 applications?

I am attempting to incorporate the jantimon/favicons-webpack-plugin into an Angular 8 project. To achieve this, I'm utilizing the @angular-builders/custom-webpack package to develop a custom webpack configuration. const FaviconsWebpackPlugin = requir ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Accessing clipboard contents upon button click using TypeScript

Seeking assistance with retrieving data from the clipboard in TypeScript after clicking on a button. Please provide guidance. Thank you! ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

Encountering difficulties testing MatTable row population in Karma testing

Can someone please assist me in identifying the issues with my coding method? I attempted to replicate the techniques demonstrated in this tutorial on Harnesses Here is an Angular component that consists of a simple data table (MatTable) connected to a re ...

Using TypeScript's Non-Null Assertion Operators in combination with square brackets []

One way to assert that an object has a certain property is by using the `!.` syntax as shown below: type Person = { name: string; age: number; gender?: string; } const myPerson: Person = { name: 'John Cena', age: 123, gender: 's ...

Creating a test scenario for a combineLatest Observable using marbles

I am working with an observable that combines two Observable<boolean> using the "or" operation with combineLatest. interface LoadingEventEmitter { isLoading$: Observable<boolean> } export class LoadingService { isLoading$: Observable<bo ...

Creating a custom autocomplete search using Angular's pipes and input

Trying to implement an autocomplete input feature for any field value, I decided to create a custom pipe for this purpose. One challenge I'm facing is how to connect the component displaying my JSON data with the component housing the autocomplete in ...

Storing images in Azure Blob Storage

I am currently using Angular 2 on the frontend and Node.js for the backend. I am facing an issue while attempting to upload a file to Azure storage blob container. Whenever I try to send the image to the API, an error occurs. Any assistance in this matter ...

Enhance your Next.js application by including the 'style' attribute to an element within an event listener

I am currently trying to add styles to a DOM element in Next.js using TypeScript. However, I keep getting the error message "Property 'style' does not exist on type 'Element'" in Visual Studio Code. I have been unable to find an answer ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

`Observing a nearby external library while running the application`

I am currently working on a main app alongside some independent libraries. To incorporate changes from the library into the main app, I have been including the .tgz file in the main app's package.json. However, this process requires me to build and pa ...

You cannot set parameters using Angular's httpHeaders post method

Seeking assistance in obtaining the authtoken from RestAPI using a specific method. While the same URL, Parameters, and Headers provide the correct response in Postman, I am encountering a 401 unauthorized error in Angular. Can someone help me identify whe ...

What is the best way to send multiple data using GetServerSideProps?

I have a challenge where I need to pass multiple sets of sanity data into a component, but I am restricted to using getServerSideProps only once. How can I work around this limitation to include more than one set of sanity data? pages > members.tsx exp ...

Is it necessary to only override the monospaced font?

Can the monospace font in Angular Material be customized for just the <code>foo</code> blocks? I want to use a font where the number zero 0 looks distinct from the letter oh O. ...

The ngx-translate/core is throwing an error message that says: "HttpClient provider not found!"

I recently downloaded the ngx-translate/core package and have been diligently following the provided documentation. However, I'm facing an issue with getting the translations to work. Here are the steps I've taken: 1] Definition in the AppModul ...

Angular 2: Retrieve current currency rates based on your location

When I apply the {{listing.sellPrice | currency : undefined : 0}} code, it only displays the symbol $. However, I would like for the currency to change based on the user's location. For instance, if someone is in Europe, their currency would be shown ...

How to automatically disable a button in reactjs when the input field is blank

I have a component called Dynamic Form that includes input fields. The challenge I am facing is how to disable the submit button when these input fields are empty, although the validateResult function fails to return false. import cn from "classname ...