extracting data from checkbox to use in an angular function upon being selected

Currently, I am creating a list of checkboxes with distinct string values: heading, paragraph, list, table, visualtitle. I believe the current approach using

(change)="onChange('heading', $event.target.checked)
may not be the best way to handle this section. Instead, I am considering utilizing the name="annotationtype" field to access the checked values in other areas. How can I retrieve these values?

<form [formGroup]="form" (ngSubmit)="submit()">
    <div class="widget-container">
      <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('heading', $event.target.checked)" />Heading</label>
      <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('paragraph', $event.target.checked)" />Paragraph</label>
      <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('list', $event.target.checked)" />List</label>
      <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('table', $event.target.checked)" />Table</label>
      <label class="checkbox-label"><input type="checkbox" name="annotationtype" (change)="onChange('visualtitle', $event.target.checked)" />Visual Title</label>
    </div>
</form>
  onChange(name: string, isChecked: boolean) {
    if (!this.urlhash)
    {
      alert("Query URL cannot be empty!!!");
    }
    else
    {
      if (isChecked) {
        this.checkedAnnotations.push(new FormControl(name));
      } else {
        const index = this.checkedAnnotations.controls.findIndex(x => x.value === name);
        this.checkedAnnotations.removeAt(index);
      }
      var url = `/sd_api/htmlview/${this.urlhash}/highlighted.html?annotypes=${this.checkedAnnotations.value.join()}&datasource=${this.datasource}`;
      console.log(url);
      this.iframe = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
  }

Answer №1

To optimize your solution, consider utilizing Angular's methodology. Specifically, make use of the Forms API provided by @angular/forms.

You can simplify your tasks by connecting the formControlName with the FromGroup object and extracting the values from the specified keys.

import { FormBuilder, FormGroup } from '@angular/forms';

export class AppComponent {
  form: FormGroup;

  constructor(private formB: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.formB.group({
      checkBox1: [false],
      checkBox2: [false],
    });
  }

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

Template

<form [formGroup]="form">
  <div class="widget-container">
    <input type="checkbox" formControlName="checkBox1" />Heading1
    <input type="checkbox" formControlName="checkBox2" />Heading2
    <div>
      <button type="button" (click)="submit()">Submit</button>
    </div>
  </div>
</form>

By following this approach, you can become more proficient in utilizing the Angular tools for common scenarios.

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 I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

What could be causing my controller to not capture the saved row?

Attempting to perform inline editing with jQgrid, I implemented the following: ...... colModel :[ ........ {name:'idProvino', index:'idProvino', editable: true}, ....... ...

Increase the size of the textarea when it is clicked on and revert back to its original size when it

My question revolves around a text area that I am trying to manipulate through jQuery. The desired functionality is to increase the height of the text area whenever someone clicks on it, and decrease the height when clicking anywhere else on the screen. & ...

Injecting variable styles into my VueJS component

I am currently working on developing a custom progress bar to visualize the percentage of completed tasks. The approach I am taking involves using v-bind:styles and passing {width: dynamicWidth + '%'} to regulate the progression of the bar. To ac ...

The Angular 9 custom directive is malfunctioning on mobile devices

I recently created a custom directive in Angular 9 that allows users to input only digits and one decimal point. While the directive works perfectly on desktop, it seems not to function at all on mobile devices - almost as if it doesn't exist within t ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

What is the reason for this Javascript regular expression only successfully matching two out of three identical strings when filtering?

To better illustrate my question, I would like to reference the following link: http://codepen.io/anon/pen/mRxOEP Here are three seemingly identical inputs from customers: <span class="customer_country" id="SW1">, Switzerland</span> <span ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

What is the best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

What is the process for setting up a single timer in a non-singleton application service?

My goal is to send a GET request every X seconds. To achieve this, I have implemented a timer in the constructor of a service which is then injected into a component for use. I want the service (as a singleton) to handle scheduling the GET requests at regu ...

Ways to display a checked or unchecked checkbox in react depending on a boolean value obtained from an API

Is there a way to display a checked or unchecked checkbox in react jsx depending on a boolean value retrieved from an api? ...

Switching icon images using JQuery based on state changes

I'm attempting to switch the background image of my webpage's "body" element when the user toggles between playing and pausing music icons. This is what the CSS for the "body" element looks like: body { background: url('https://s3-us-wes ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

How can Data Value be displayed instead of percentage in Gebo Pie Charts?

$.plot(elem, data, { // // series : { pie : { show : true, highlight : { opacity ...

Issue: TypeError - 'process.env' can only accept a configurable while installing windows-build-tools

Unable to successfully download installers. Encountered an error: TypeError: 'process.env' can only accept a configurable, writable, and enumerable data descriptor. I attempted to resolve this issue by running the command npm install --global wi ...

Navigating through child elements within a div using JavaScript

I recently coded a div using this snippet... let sidebarBox = document.createElement("div"); sidebarBox.id = "sidebarBox"; ...and then I created a second div like so... let sidebarAd = document.createElement("div"); sidebarAd.className = "sidebarAd"; B ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...