Setting a default check on a checkbox within an ngFor loop in Angular 2

I'm attempting to initialize a default value as checked for a checkbox within my ngFor loop. Here is an array of checkbox items I am working with:

tags = [{
  name: 'Empathetic',
  checked: false
}, {
  name: 'Smart money',
  checked: true
}, {
  name: 'Minimal help after writing check',
  checked: false
}, {
  name: 'Easy term sheet',
  checked: true
}];

This is the HTML structure I am using:

<div class="form-group">
  <div class="form-check" *ngFor="let tag of tags;">
    <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        name="tagOptions"
        [(ngModel)]="tag.checked">
      {{tag.name}}
    </label>
  </div>
</div>

The expected outcome is to have 2 checkboxes checked and 2 unchecked, but currently all are unchecked. I have experimented with different methods such as [checked]="tag.checked", however, it does not seem to be working as intended.

Answer №1

This solution resolved my issue with managing checked and unchecked checkboxes, allowing me to maintain control over changes in my variables.

Below is the code snippet for achieving this functionality:

<div class="form-group">
  <div class="form-check" *ngFor="let tag of tags; let i = index;">
    <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        name="tagOptions"
        (change)="changeCheckbox(i)"
        [checked]="tag.checked">
      {{tag.name}}
    </label>
  </div>

.ts file:

  changeCheckbox(tags, i) {
    if (tags) {
      this.tags[i].checked = !this.tags[i].checked;
    }
  }

Answer №2

Opt for using the checked property over ngModel,

 <div class="form-group">
      <div class="form-check" *ngFor="let tag of tags">
        <label class="form-check-label" for="tag{{tag.value}}">
          <input
            class="form-check-input"
            type="checkbox"
            id="tag{{tag.value}}"
            name="tagOptions"
            [checked]="tag.checked">
          {{tag.name}}
        </label>
      </div>
   </div>

DEMO

Answer №3

Although this thread may be old, I recently encountered a similar issue related to the name tag. The problem arises because the name tag is the same for every checkbox, causing the Form to raise complaints. You can address this issue by implementing the following solution:

<div class="form-group">
  <div class="form-check" *ngFor="let tag of tags;">
    <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        [name]="tag.name"
        [(ngModel)]="tag.checked">
      {{tag.name}}
    </label>
  </div>
</div>

Answer №4

This question really helped me out with my brain health haha. I made a little "upgrade" to the correct answer:

HTML:

<div class="form-group">
      <div class="form-check" *ngFor="let tag of tags; let i = index;">
        <label class="form-check-label" for="tag{{tag.value}}">
          <input
            class="form-check-input"
            type="checkbox"
            id="tag{{tag.value}}"
            name="tagOptions"
            (change)="changeCheckbox($event, i)"
            [checked]="tag.checked">
          {{tag.name}}
        </label>
      </div>

TS:

changeCheckbox(event, index){
      this.tags[index] = event.target.checked;
    }

Answer №5

Utilize the name attribute as an identifier instead:

   <label class="form-check-label" for="tag{{tag.value}}">
      <input
        class="form-check-input"
        type="checkbox"
        id="tag{{tag.value}}"
        name="tag{{tag.value}}"
        [(ngModel)]="tag.checked">
      {{tag.name}}
    </label>

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

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

Obtaining gender information by utilizing checkboxes in Angular 7

I have developed an Angular application that enables users to filter samples by gender using checkboxes. The options include male, female, or both genders selected. Currently, the filtering works for selecting either male or female individually, as well as ...

Why do optional values of objects remain optional when being checked in an if statement in Typescript?

Recently at work, I encountered this code snippet and was left wondering why Typescript couldn't comprehend the logic behind it. If 'test' in the object can either be undefined or a string, shouldn't it logically infer that within an if ...

Issues with Form Field Appearance in Angular Material 2

I've been attempting to give my form inputs a fill appearance in my application. I imported MatFormFieldModule and MatInputModule, and included appearance="fill" in my mat-form-field element. However, I'm not seeing the desired fill effect. Am I ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

One of the essential components in Angular is currently absent

After integrating Angular4 with Visual Studio 2017 following the steps outlined in this article, I realized that my setup also involved using Nodejs 8.6.0 and npm 5.4.2 - which were the latest versions at the time. Despite having vs2017 generate a fold ...

Disarrayed generic parameters in TypeScript

The title of the question may not be perfect, but it's the best I could do. Imagine a scenario where there is a function that accepts a callback along with an optional array. The callback takes an index and another optional array as parameters, and t ...

Testing the Window beforeunload event method in an Angular unit test: A guide

Currently, I am actively involved in a project using Angular 8. One of the features I implemented was to show a confirm prompt when a user tries to navigate away from the site. This functionality was added by integrating the following function into my com ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

Tips for arranging Angular Material cards in columns instead of rows

I am currently developing a web application using Angular, and I've encountered an issue while trying to display cards in a vertical layout rather than horizontally. My goal is to have the cards fill up the first column (5-6 cards) before moving on to ...

Is there a way to determine if there is history in Location.back in Angular 2 in order

I have a button that triggers Location.back(). I only want to show this button when there is history available. Is there a way to check if the location has any history, or if it can go back? Alternatively, is there a method for me to access the history my ...

Cannot use a 'string' type expression to index a 'Request<ParamsDictionary, any, any, Query>' type

Currently, my goal is to develop a middleware that can validate the input data in a request. export function validator(schema: Joi.ObjectSchema, key: string) { return function (req: Request, res: Response, next: NextFunction): void { try { Joi ...

Trouble displaying JSON markers on Ionic Google Maps

Looking for assistance related to this issue? Check out Ionic Google Maps Markers from JSON In my Ionic App with Google Maps integration, I'm facing an issue where although the map displays correctly, the pin markers are not showing up. It seems like ...

Compiler unable to determine Generic type if not explicitly specified

Here is a simple code snippet that I am working with: class Model { prop1: number; } class A<TModel> { constructor(p: (model: TModel) => any) {} bar = (): A<TModel> => { return this; } } function foo<T>(p: ...

Tailored component properties for React applications

I am currently working on configuring discriminative component props. Check out my code snippet below: import React, { ReactNode } from 'react' type SelectionModalProps<T> = ( | { multiSelect: true onSubmit: (data: T[]) => ...

Steps for integrating third party modules into an Angular library built with the CLI

Looking to integrate Pure.css module into an Angular library developed with the CLI's generate library command. In my workspace app, I used the generate library command to create a new library. After successfully creating and linking it to another pr ...

What is the procedure for renaming an item within a basic array in Angular?

I am working on a project in Angular and have constructed an array. I am now looking to change the name of one of the items in this array. While I have figured out how to rename keys in an array, I'm still unsure about how to do so for its values. ...

Angular - Utilizing FormArrayName within child components

There are three main components involved: consent consent-scope-list consent-scope-item consent includes a FormGroup that houses two FormArrays. consentForm = this.fb.group({ identityScopes: this.fb.array([]), resourceScopes: this.fb.array([]) }); ...