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

Guide to building a static method generator in TypeScript

Currently, I am working on creating a static method factory function in TypeScript. In my previous implementation using ES6, everything was functioning well and meeting my expectations. However, upon transitioning to TypeScript, I encountered a type-castin ...

Align and resize image using CSS styling

Seeking assistance on centering and cropping images using CSS. Tried implementing the technique from this specific article. However, experiencing inconsistencies in device UI output. Can someone shed light on this behavior? Scenario: The objective is t ...

Consequences of eliminating Angular component wrapper tags from the DOM

Imagine there is a component named <hello-world> with the following HTML template: <div>Hello World!</div> When this component is used and inspected in the DOM, it shows up like this: <hello-world> <div>Hello World!</div ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

Utilize Ionic for mobile development - Demonstrating the process of displaying a save prompt on Android devices

I am trying to find a way to export JSON as a file using Ionic running as an APK on Android. While I can easily do this when using a browser on PC, it seems impossible on Android as I am unable to download the file. I have tried using "a link" and ngx-fil ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

The function __WEBPACK_IMPORTED_MODULE_3_ionic_native__.a.open is returning an error

Is there a way to troubleshoot and resolve the following error: WEBPACK_IMPORTED_MODULE_3_ionic_native.a.open is not a function while utilizing the NishanthKabra/Ionic2_GoogleCalendar solution. I am interested in integrating Google Calendar into my Io ...

What is the best way to attach events to buttons using typescript?

Where should I attach events to buttons, input fields, etc.? I want to keep as much JS/jQuery separate from my view as possible. Currently, this is how I approach it: In my view: @Scripts.Render("~/Scripts/Application/Currency/CurrencyExchangeRateCreate ...

Visual Studio - Error TS1005 'Unexpected token'

After spending nearly 5 hours scouring the internet for a solution, I am still unable to resolve this persistent issue. The responses I've found so far do not seem to address the specific problem I'm facing. Although I have upgraded the tsc vers ...

Tips for resetting and enabling file uploads with ng2-file-upload

My file upload functionality is working smoothly using ng2-file-upload. However, I am facing a challenge in handling server-side errors and resetting the file uploader. How can I achieve this? Below are the snippets of code that I am currently using: HTML ...

Capturing page titles accurately for timeonsite tracker in a single-page Angular app is challenging when navigating to other pages

Implemented the timeonsite JS tracker in my Angular web application using HTML tags as shown below, <script type="text/javascript"> var Tos; (function(d, s, id, file) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementByI ...

Stringified HTML code showcased

When working with Angular, I have encountered an issue where I am calling a function inside an .html file that returns a string containing a table element. My goal is to convert this string into HTML code. I attempted to use [innerHtml]: <p [innerHtml ...

Tips for accessing child elements within an Angular component

I'm struggling to get a reference of child elements within a component. I have experimented with ElementRef, TemplateRef, QueryList, ViewChild, ViewChildren, ContentChild, and ContentChildren without success. <app-modal> <section #referenc ...

Is there a way to modify an image that has been dynamically inserted in an Angular application?

I'm facing an issue with dynamically added input files in Angular. Whenever I upload a file, it changes all the images of the input files instead of just the one I want to target. How can I resolve this problem? Please help. images = [ {url: &ap ...

Discovering Typescript: Inferring the type of a union containing specific strings

I am working with a specific type called IPermissionAction which includes options like 'update', 'delete', 'create', and 'read'. type IPermissionAction = 'update' | 'delete' | 'create' | ...

What methods can be utilized to gauge loading speed in Angular2?

Currently, I am working with Angular2 and I am looking to measure the loading time of my application. Within the app, there are 3 child components, two of which contain very heavy content that affects performance. In an attempt to improve this, I have ut ...

Calculating the time difference between two dates in the format yyyy-MM-ddTHH:mm:ss.fffffff can be done by following these steps

Can someone help me figure out how to calculate the difference in days between the date and time 2021-02-23T08:31:37.1410141 (in the format yyyy-MM-ddTHH:mm:ss.fffffff) obtained from a server as a string, and the current date-time in an Angular application ...