What is the best way to retain all checkbox selections from a form upon submission?

I have a batch of checkboxes that correspond to the profiles I intend to store in the database.

HTML:

<tr *ngFor="let profile of profiles | async">
  <input type='checkbox' name="profiles" value='{{profile.id}}' ng-model='profile.checked'> {{profile.name}}
  <td>
    {{profile.id}}
  </td>

Next, in the TypeScript file, I aim to loop through the list of profiles and invoke the create profile service for those that are checked. The service expects a single profile, so I need to iterate through and verify if the checkbox is selected before calling the Spring Boot service.

Any suggestions on how to achieve this?

TYPESCRIPT.TS

//Your code recommendations here

//Calling the service
this.profileService.createProfile(profile)

Answer №1

Make sure to assign an Id to input checkboxes similar to the example below:

id="profile{{profile.id}}"

profileData:any=[];

  ngOnInit() {
    this.fetchProfiles();
    }

 fetchProfiles() {
    this.profileService.getProfileList()
      .subscribe(res=> {
        if (res) {
          this.profiles = res;
          this.profileData = this.profiles;
         }
      })
  }

 submit() 
  {

    for(var i= 0;i < this.profileData.length ; i++){  
    var id = "profiles" + this.profileData[i].id;
    var isChecked = (<HTMLInputElement>document.getElementById(id)).checked;   
    if(isChecked)
    {
    this.profileService.createProfile(profile)
     }
    else
     {

      }
  }

Following these steps should resolve your current issues.

Answer №2

For clarity, I will provide the complete code below:

HTML:

<h3>Create User</h3>
<div [hidden]="submitted" style="width: 400px;">
    <form (ngSubmit)="onSubmit()">
        <div class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" id="name" required [(ngModel)]="user.name" name="name">
        </div>

        <div class="form-group">
            <label for="phone">Phone</label>
            <input type="text" class="form-control" id="phone" required [(ngModel)]="user.phone" name="phone">
        </div>

        <div class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control" id="email" required [(ngModel)]="user.email" name="email">
        </div>

        <h4>Profiles</h4>
        <table class="table table-striped">
         <thead>
           <tr>
             <td>Enable/Disable</td>
             <td>ID</td></tr>
         </thead>
         <tbody>
            <tr *ngFor="let profile of profileservice | async">
             <input type='checkbox' name="profile" value='{{profile.id}}' id="profile{{profile.id}}" ng-model='profile.checked'> {{profile.name}}
             <td>
               {{profile.id}}
           </td>
           <td>
           </td>
       </tr>
   </tbody>
</table>

<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>

<div [hidden]="!submitted">
    <h4>You submitted successfully!</h4>
</div>

TS:

import { UserService } from './../user.service';
import { User } from './../user';
import { Component, OnInit } from '@angular/core';
import { ProfileService } from './../profile.service';
import { Profile } from "./../profile";
import { Observable } from "rxjs";
import { UserProfileService } from './../userprofile.service';

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {

  user: User = new User();
  submitted = false;
  profilesservice: Observable<Profile[]>;
  response: any;
  constructor(private userService: UserService, private profileService: ProfileService, private userprofileService: UserProfileService) { }

  ngOnInit() {
    this.profilesservice = this.profileService.getPerfisList();
  }

  newUser(): void {
    this.submitted = false;
    this.user = new User();
  }

save() {
    this.userService.createUser(this.user)
      .subscribe(res => {
        this.response = res;
        console.log(res);
        this.user = new User();

        for(var i= 0;i < this.profilesservice.length ; i++){  
          var id = "profiles" + this.profilesservice[i].id;
          var resval = (<HTMLInputElement>document.getElementById(id)).value;   
          if(resval)
          {
            //Here I want to call this.userprofileService.createUserProfile(profile)
          }
          else
          {
            alert(2);
          }
        }
    });
  }

  onSubmit() {
    this.submitted = true;
    this.save();
  }
}

Answer №3

Attempting to make changes to the profile? To successfully edit, adjust ng-model='profile.checked' to [(ng-model)]='profile.checked'. Your current syntax will not establish a connection.

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

Using a generic type as a value in an abstract class <T, K extends keyof T> allows for flexible and dynamic data manipulation

Currently, I am in the process of transferring some logic to an abstract class. Let's look at the abstract generic class with specific constraints: abstract class AbstractVersion< TModel extends object, TProperty extends keyof TModel, T ...

Exploring the Impact of 2 HostBindings on Class Generation from Inputs in Angular 4

I'm struggling with the code in my component, which looks like this: @Component({ selector: "home", templateUrl: "./home.html" }) export class Home { constructor() {} @HostBinding("class") @Input() public type: string = "alert" @HostBindi ...

Tips for styling the Button component in the shadcn/ui library for maximum impact

I'm currently working on a project using the shadcn/ui library. How can I properly customize it to meet my specific needs? For example, let's say I require an extra large red rounded Button for a call-to-action button in my project. What would be ...

Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript. getDiscount(){ let getDisc = []; getDisc.push({ price: Number(this.commonService.getP ...

Error message stating: "The 'MktoForms2' property is not recognized within the scope of 'Window & typeof globalThis'."

Encountering the following error message: (Property 'MktoForms2' does not exist on type 'Window & typeof globalThis') while working with react and typescript useEffect(() => { window.MktoForms2.loadForm("//app-sj11.marke ...

What type of event does the Input element in material-ui v1 listen for?

I'm currently grappling with material-ui v1 as I search for the appropriate event type for input elements. Take a look at the code snippet below: <Select value={this.numberOfTickets} onChange={this.setNumberOfTickets}> .... Here is the impleme ...

Skip creating declarations for certain files

src/ user.ts department.ts In the scenario outlined above, where there are two files in the src directory (user.ts and department.ts), is there a way to exclude the generation of declaration files specifically for department.ts when running tsc wi ...

Creating an Angular 2 project with DevExtreme in Visual Studio 2017/2015: A step-by-step guide

I would appreciate some guidance on setting up an Angular 2 project with DevExtreme control using Visual Studio 2017/2015. Specifically, I am interested in utilizing the control demonstrated at . Your assistance would be greatly appreciated. ...

Navigating from Angular 16 to Flask and experiencing browser refresh: A guide on redirecting to the 'root' path

As a newcomer to Angular, I was given the task of developing a single-page application (SPA) user interface frontend that communicates with a Flask server. Things were going smoothly until I encountered an issue when the user decides to hit the refresh but ...

Center align the mat-expansion-panel material component in a vertical orientation

When working with the mat-expansion-panel component alongside a mat-accordion, I've encountered an issue where the items are not aligning vertically at the center/middle. I'm unsure of the proper method to achieve vertical alignment for the conte ...

How can I use a string from an array as a key in an object using TypeScript?

I have been utilizing a for loop to extract strings from an array, with the intention of using these strings as object keys. Although this code successfully runs, TypeScript raises a complaint: const arr = ['one', 'two']; const map = ...

Top approach for Constructing Angular Front-End Forms with User Input

Greetings to all who happen upon this message, thank you for taking the time to potentially offer assistance! In my past experiences working with Wordpress (PHP), I utilized a plugin called Advanced Custom Fields from advancedcustomfields.com. This plugin ...

Enhance React component props for a styled component element using TypeScript

Looking to enhance the properties of a React component in TypeScript to include standard HTML button attributes along with specific React features such as ref. My research suggests that React.HTMLProps is the ideal type for this purpose (since React.HTMLA ...

Retrieving Data from API in Angular 6/7 upon Navigating Back to Previously Visited Page

I'm currently navigating my way through angular and encountering a small hurdle. I aim to guide a user to a data entry page where most fields are pre-filled by retrieving data from the database based on a record id. The user then modifies some fields, ...

Tips for avoiding storage issues in Angular Server-Side Rendered application using guards and services (Angular V17)

Is there a way to prevent undefined localStorage/Sessionstorage errors in Angular V17 SSR apps without using the old platformId? I am looking for an equivalent of afterNextRender that can be used in services or guards, whether they are functional guards or ...

Issue encountered with Typescript and Request-Promise: Attempting to call a type that does not have a call signature available

I have a server endpoint where I want to handle the result of an asynchronous request or a promise rejection by using Promise.reject('error message'). However, when I include Promise.reject in the function instead of just returning the async requ ...

Outputting a JS file per component using Rollup and Typescript

Currently, I am in the process of developing a component library using React, TypeScript, and Rollup. Although bundling all components into a single output file index.js is functioning smoothly, I am facing an issue where individual components do not have ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Error encountered when attempting to pass i18next instance to I18nextProvider

Issue: Error message: Type 'Promise' is missing certain properties from type 'i18n': t, init, loadResources, use, and more.ts(2740) index.d.ts(344, 3): The expected type is derived from the property 'i18n' declared within ty ...

Using TypeScript's conditional types for assigning types in React

I'm tasked with creating a component that can belong to two different types. Let's call them Type A = { a: SomeCustomType } Type B = { b: SomeOtherDifferentType } Based on my understanding, I can define the type of this component as function C ...