Angular allows you to bind a Checkbox input type to be checked by default

Working on an Angular 5 application with checkboxes. Data is retrieved from the database and mapped to a JavaScript object. Having trouble configuring the 'Selected' value. Currently, all checkboxes are checked in the result.

In the code below, 'option: [] --> 'optionSelected' is defined based on whether it is selected or not.

https://i.sstatic.net/VlDpe.png

Template

 <div *ngSwitchCase="'checkbox'"> <small>checkbox</small>
       <div *ngFor="let opt of question.options" >
            <label class="container-vertical"> {{opt.value}}
                <input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [checked]="opt.optionSelected" /> 
                <span class="checkmark2"></span>
            </label>
       </div>      
 </div> 

Tried using ngModel as well. The property 'value' holds the ID of the selected key, but still, all checkboxes are checked in the final result.

<input type="checkbox" [formControlName]="question.key" [name]="opt.name" [value]="opt.key" [(ngModel)]="question.value" />

Component

 else if (questionElementType=="checkbox")
 {
   let _checkBox = new CheckBoxQuestion ({
     consultationId: questionsList[key].consultationId,
     questionId: questionsList[key].questionId,
     questionElementType: questionsList[key].questionElementType[0].title,           
     questionType: questionsList[key].questionType,
     title:questionsList[key].title,
     displayId: questionsList[key].displayId,
     key: questionsList[key].questionId,     
     value: questionsList[key].answer.length<=0 ? null : questionsList[key].answer[0].answerValue.toLowerCase(),
     label: questionsList[key].title, 
     order: 7,
     options: questionsList[key].answerOptions.map(function(item){
       return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": item.preDefineAnswerOptionId==questionsList[key].answer[0].answerValue? "true" : "false"}
    }),
   });

     this.mappedQuestions.push(_checkBox);
 }

Answer №1

To ensure the checkbox remains unchecked, make sure its [value] binding is false.

Remember that both "true" and "false" are considered non-empty strings, resulting in an evaluation of true.

If you convert "false" to false, it will function as expected.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
<input type="checkbox" [(ngModel)]="checkbox1" /> "true"
<input type="checkbox" [(ngModel)]="checkbox2" /> "false"
<input type="checkbox" [(ngModel)]="checkbox3" /> true
<input type="checkbox" [(ngModel)]="checkbox4" /> false
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  checkbox1 = 'true';
  checkbox2 = 'false';
  checkbox3 = true;
  checkbox4 =  false;
}

https://i.sstatic.net/pLXuW.png

Check out the live demo here

Answer №2

Feel free to utilize this:

 <input type="checkbox" [(ngModel)]="active" [checked]="true" 
(change)="isAactiveChange($event)" >

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

How can you determine the length of an Array in *ngFor while utilizing the Async pipe in Angular?

I currently have the following code snippet: <mat-toolbar-row *ngFor="let idp of Idps | async; last as isLast"> and I am looking to access the length of it for the following elements: <button [disabled]="(Idps| async)?.length===1" [ngClass]="{ ...

What is the best way to implement an IF THEN ELSE statement using ngStyle in Angular?

How can I make rows in a table highlight based on the STATUS value? Currently, I have it set up to show yellow if the STATUS is 1 using the following code: [ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : '&a ...

A solution for resolving the RuntimeException in genuitec's TypeScript Editor for Eclipse Oxygen

After setting up a fresh Eclipse Oxygen and installing the Angular IDE from Genuitec, I encountered an issue on the second day when I opened a project and accessed a *.ts File. The error message displayed was: java.lang.RuntimeException: java.lang.Illegal ...

How do I specify the return type of a function in Typescript that can return more than one type?

I am facing a situation where I have a method called getFilters that retrieves various types of values. getFilters(): IListFilteringType {...} type IListFilteringTypeMultiSelect = (string | number)[]; type IListFilteringType = boolean | string | number | ...

Splitting angular2 and browserify into individual vendor and app bundles can help prevent import errors

I am currently developing an Angular2 application and I am aiming to use gulp and browserify for the build process. By utilizing tsify, I was able to create a standalone bundle.js file, which ended up being 1.4M in size after minification. What I desire ...

Optimized Image Loading with Angular17's ngSrc

Currently experimenting with Angular 17: // typescript get getWidth(): number { // this._el is an inject(ElementRef); const width = +this._el.nativeElement.querySelector( '[id="fs-img-container"]' ).clientWidth; ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

What steps should I take to ensure that TypeScript acknowledges the validity of my object assignment?

Trying to implement this code: type A = { b: false, } | { b: true, p: string; } function createA(b: boolean, p: string | undefined): A { if (b && p === undefined) { throw 'Error'; } const a: A = { b, ...

Easily Organize Your Data with Kendo React Grid: Rearrange Columns and Preserve Your Custom Layout

Currently, I am working on implementing a Kendo React grid with the option set to reorderable={true} for allowing column reordering. However, I am facing difficulty in determining how to save the new order of columns. Which event should I use to detect whe ...

Import TypeScript files with RequireJS

I'm looking for some clarification on RequireJS. Right now, I compile all my Typescript files into one JS file. If I switch to RequireJS, does that mean I won't have just one JS file anymore? As I understand it, RequireJS dynamically loads JS f ...

I possess a table that showcases MatIcon buttons. Upon clicking on a button, two additional buttons should appear at the bottom of the table

I am working on a table that contains mat-icon-buttons. When the button is clicked, it should display 2 additional buttons at the end of the table. Upon clicking the first button, its color changes from primary to red, and I would like to add two more butt ...

Why do my subscriptions in Angular 9 load sequentially rather than simultaneously?

In my Angular 9 project, I am trying to load a series of objects containing image data. My goal is to first load all the objects and then fetch the image data for each object afterwards. In the `ngOnInit` function in my component.ts file, I have the follow ...

Encountering an error message that states "Unable to read property 'next' of undefined" while utilizing the async

Operating a service similar to this involves simulating an API call. import { Injectable } from '@angular/core'; import { Observable, Subscriber} from 'rxjs'; import { DeviceStatus } from '../models/device-status-model'; @I ...

Encountering issues with dependencies while updating React results in deployment failure for the React app

Ever since upgrading React to version 18, I've been encountering deployment issues. Despite following the documentation and scouring forums for solutions, I keep running into roadblocks with no success. The errors displayed are as follows: $ npm i np ...

The process of accessing an array of arrays (JSON) using Angular 2

After receiving this JSON response places":[{"libPlace":"Le Colis\u00e9e","idPlace":1},[{"dateEventPlace":"2017-03-19T08:09:00+0000"},{"dateEventPlace":"2017-03-19T14:19:00+0000"},{"dateEventPlace":"2017-03-24T14:08:00+0000"}],{"libPlace":"ABC","idPl ...

Persistent Ionic tabs after user logs out - keeping tabs active post-logout

My Ionic app features tabs and authentication. While the authentication process works perfectly, I am facing an issue with the tabs still displaying after logging out. Below is my login method: this.authProvider.loginUser(email, password).then( auth ...

collaborating on data within closely related components in a table display

I am trying to figure out the best way to pass data among sibling components. For example, let's say I have a data entry grid structured like this: <tr *ngFor="let item of frm.controls.items.controls; let i=index" [formGroupName]="i"> <td ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

Unfortunately, my capabilities do not allow me to execute the command 'ng build --configuration production

This is the issue that I am facing and need assistance: Error: src/app/app.component.html:1:1 - error NG8001: 'fuse-progress-bar' is not recognized as a valid element: If 'fuse-progress-bar' is an Angular component, please ensure that ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...