Ways to access the values of checkboxes that are initially checked by default

Recently, I was working on a project that involved multiple checkboxes. My goal was to have the checkboxes pre-checked with values in the form (using reactive form). Users should be able to unselect the boxes as they wish and the data would be stored accordingly. You can check out the StackBlitz of the project. I managed to get the checkboxes checked initially, but ran into an issue when hitting the submit button - there was no data being logged to the console. I suspect it's a binding problem, but I'm struggling to pinpoint the exact issue. Can anyone provide assistance? Thanks in advance.

Here is the code snippet:

<form [formGroup]="form" (ngSubmit)="submit()">
  <div class="form-group">
    <label for="website">Website:</label>
    <div *ngFor="let web of websiteList">
      <label>
        <input
          type="checkbox"
          [value]="web.id"
          (change)="onCheckboxChange($event)"
          [checked]="web.isSelected"
        />
        {{ web.name }}
      </label>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit</button>
</form>
  form: FormGroup;
  websiteList: any = [
    { id: 1, name: 'HDTuto.com', isSelected: true },
    { id: 2, name: 'HDTuto.com', isSelected: true },
    { id: 3, name: 'NiceSnippets.com', isSelected: true },
  ];

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      website: this.fb.array([], [Validators.required]),
    });
  }

  ngOnInit() {}
  onCheckboxChange(e: any) {
    const website: FormArray = this.form.get('website') as FormArray;
    console.log('checking ->', e);

     if (e.target.checked) {
      website.push(new FormControl(e.target.value));
      console.log('website ->', website);
    } else {
      //console.log(e);
      const index = website.controls.findIndex((x) => {
        console.log('x.value ->', x.value);
        console.log('target.value ->', e.target.value);
        x.value === e.target.value;
      });

      website.removeAt(index);
    }
  }
  submit() {
    console.log(this.form.value);
  }

Answer №1

https://stackblitz.com/edit/angular-ivy-qar4ph-update?file=src/app/app.component.ts Take note of the modifications made to the template:

  1. Added formArrayName attribute to checkboxes container and formControlName attribute to input element.
  2. Eliminated change and checked attributes

Within the component typescript file:

  1. Included initial form array values
  2. Implemented mapping for submit method
  3. Deleted onCheckboxChange function

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

Tips for minimizing the number of map calls in an Angular Web App using agm-core

Our team has developed a user-friendly application using Angular with 5 pages, each featuring a Google map. The main reason for choosing Angular was to minimize the number of Map calls per user session to just 1; previously in our javascript-based app, thi ...

Tips for maintaining a user's session post-login with Passport and Express JS

I recently set up a node backend using express and integrated Passport for authentication purposes. My application has a route called /login for logging in and another route called /me to retrieve information about the currently logged in user. Below is t ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

JavaScript Deviance

I am facing an issue with my JS code while trying to send form data to a .php file via AJAX. The problem occurs when the input fields are filled - for some reason, my client-side page refreshes and the php file does not get executed. However, everything wo ...

Finding your site's First Contentful Paint (FCP) can be done by analyzing the

After doing some research on Google insights, I came across information about FCP. However, I'm still unsure about how to determine my site's FCP and other relevant metrics. If anyone could provide me with more information or share detailed link ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

Obtain the number of elements rendered in a React parent component from a switch or route

I'm currently working on a component that is responsible for rendering wrapper elements around its children. One challenge I'm facing is determining which elements are actually being rendered as children. I've implemented functions to ignore ...

Unable to submit form with Jquery

Having some trouble with my form submission using Jquery. The submit part of my code seems to be malfunctioning, and I can't pinpoint the issue. <?php if(!isset($_SESSION["useridentity"])){ die(header("Location:index.php")); } ...

Error: Attempting to access the 'email' property of an undefined element during registration

I am facing an issue with my if statement. Below is the code snippet that I am currently working with: ` app.post('/register', redirectHome, async (req, res, next)=>{ try{ const email = req.body.email; let password = req.bo ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

Remove any unnecessary characters from the beginning of the string and keep track of the total number of spaces removed

How can I determine the number of characters that have been removed from the beginning of a string? This string is retrieved from a textarea input, and knowing this information will help me calculate the new position of the cursor selection. While $.trim( ...

How do I store the result of an Ajax request as a variable in a different function within a React component?

One of the challenges I'm facing involves making an ajax call that retrieves a list of movies, and then running another function with a separate ajax call to fetch the genre names. Since the first call only provides the genre IDs, I need to match each ...

Issue: When a function within a subscribe method does not return a value and its declared type is not 'void' or 'any', a TypeScript error occurs

In my Angular 2 project, I've created a basic service to check if the user is logged in. This service verifies the existence of the user object within the FirebaseAuth object. However, I encountered an error stating "lack of return statement" even tho ...

Issue Installing Npm Package (detected 23 security vulnerabilities)

My attempt to install the package resulted in an error message. How can I resolve this issue? ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Can you explain the purpose behind using this syntax within the subscribe function?

.subscribe(data=> { this.timezones = data; } Is the 'data' variable used in the .subscribe() method the same as the one declared in the constructor (private: data)? What does the arrow symbol mean and what is its purpose? export class X ...

Using Firebase's REST API to send a PATCH request

Greetings, I am currently working on an Angular application that utilizes Firebase. I need to update a record in my database and I am using the REST API for this purpose: this.http.patch(fireBaseConfigDBEndpointCloudReference + this.logIn.getUser().valu ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Display the column every time the user types something into the search bar

Currently working on an Angular project and I'm trying to figure out how to make the middle column visible whenever the user enters text in the search bar. At the moment, I have a search bar for user input and three flex columns. The middle column is ...

Interacting between two Angular 4 applications

I came across solutions here and here related to this issue, but they seem to be for an older beta version of Angular (I believe now we should bootstrap a module, not a component; also, I couldn't find the bootstrap function in the documentation for v ...