What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this?

**Stackblitz link:** :

https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fapp.component.html

HTML:

  <h6 class="col-12 emr_header m-t10">Immune
    <input class="pull-right top-4" type="checkbox">
  </h6>
  <div class="row bg-white m-0 p-t10 brd-blu" id="record_allergy" *ngFor = "let data of immune">
    <div class="col-sm-6">
      <label class="col-sm-5">Status :</label>
      <label class="col-sm-6">{{data.Status}}</label>
    </div>
    <div class="col-sm-6">
      <label class="col-sm-4">WasNotGiven :</label>
      <label class="col-sm-7">{{data.WasNotGiven}}</label>
    </div>
  </div>

Submit button Html:

<div class="col-12 m-t20 m-b20 text-right">
    <a class="share" (click)="exportEmr(data)">Export to EMR</a>
    <a class="reset">Cancel</a>
  </div>

TS:

  exportEmr(data) {
        console.log(data);
      }

Answer №1

One observation is the presence of multiple id attributes with identical values, which should be unique.

HTML:

<div class="tabcontent hide emr_records" id="EMR_RecordsList" style="display: block;">
    <h6 class="col-12 emr_header">Allergy
        <input class="pull-right top-4" type="checkbox" #allergyViewChild>
    </h6>
    ...

TS:

export class AppComponent  {
    @ViewChild('allergyViewChild') allergyViewChild: ElementRef;
    ...

Visit this link for more details.

Answer №2

Utilize the change event in order to insert your data once a user selects the desired item.

  1. Implement the change event on your input elements. For example:

    <input class="pull-right top-4" type="checkbox" value="allergy" 
           (change)="updateData($event)">
    
  2. Create a new variable:

    data: any[] = [];
    
  3. Your updateData function should manage the change event from the input:

    updateData($event) {
      if ($event.checked) { 
        // Your logic when the user selects the checkbox
        const section = $event.target.value; // the assigned value of the checkbox
        this.data.push(this[section]);
      } else { 
        // Your logic when the user deselects the checkbox
        console.log('Your logic for when the user deselects, perhaps you want to remove the                         
        item from the array');  
      }
    }
    

Answer №3

Make sure to complete the task in an "angular style"

//initialize an array for checks
checks:boolean[]=[]

//include ngModel in your .html file
<h6 class="col-12 emr_header">Allergy
        <input ([NgModel)]="check[0]" class="pull-right top-4" type="checkbox" #allergyViewChild>
    </h6>
    ...
<h6 class="col-12 emr_header">Careplan
        <input ([NgModel)]="check[1]" class="pull-right top-4" type="checkbox" #careplanViewChild>
    </h6>
    ....

//Utilize spread operator in submit function
let result:any{}
if (check[0])
   result=this.allergy;
if (check[1])
   result={...result,this.careplan}
...

You may also consider storing your variables in a single array for better organization

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

Incorporating an event listener for 'storage' in jQuery using JavaScript

Can anyone tell me how to achieve the same functionality as javascript addEventListener in JQuery? I have been attempting to use it with .bind(), but it seems not to recognize the "storage" keyword. When I tried using 'e' within this context, it ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

A dynamic input field will appear on the page following the closing </form> tag

I encountered an unusual situation where upon clicking a button with the id #fusk, dynamic elements are added. Here is the code snippet: $('#imgc').append( "<div class='divi'>" + "<input type='hidden' name=' ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...

Is it true that node.js arrays can be considered as hashmaps?

Surprisingly, this code is functioning properly in node.js: var arr = new Array(); // also works: var arr = []; arr[0] = 123; arr['abc'] = 456; arr; // node.js: [ 123, abc: 456 ], chrome: [123] I've always believed that an array preserves ...

Utilizing Ajax and jQuery to extract information from an XML file based on an identification number

Currently, I am looking for a way to showcase a specific product with its description from my XML file by using the product's ID. The structure of my XML file is shown below: https://i.sstatic.net/wFWgW.png Below is the JavaScript code I am using: ...

What is the method to retrieve values passed to the next() function in Node.js?

For my current project, I am utilizing Node.js in combination with Express.js to develop the back-end. In middleware functions, next() is commonly used to progress through the chain until reaching the final app.VERB() function. My question is, at what poi ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

Custom Tooltips arrow is not receiving the CSS styling

I have implemented ReactTooltip from the ReactTooltip library You can view an example here Component Setup <ReactTooltip className={styles.customTheme} id={id} place={placement} effect="solid"> {children} </ReactTooltip> Stylin ...

The setter function for a component is being triggered twice when utilizing the slice method with @Input in Angular 4

Using two-way data binding in Angular 4 to pass an array to another component can be done like this: component.ts import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component. ...

When the component is initialized, the computed property is not being evaluated

My maps component initializes a Google map, adds markers based on props passed from the parent, and sets the correct bounds of the map. However, the markers are added through a computed property to make it reactive. Everything seems to be working fine, exc ...

Using an iframe containing a link to trigger the opening of a colorbox in the

Recently, I encountered a challenge regarding an iframe containing a bar graph. I wanted to achieve that when the graph is clicked, it would open a colorbox with a more detailed graph from the "PARENT" of that iframe. Initially, I managed to get the ifram ...

Merge the movements of sliding a block along with the cursor and refreshing a sprite displayed on the block

Confronted with the challenge of combining 2 animations, one to move the block behind the cursor inside the container and the other to update the sprite on the block. Let me elaborate further on my issue. The block should only move when the cursor is insi ...

learning how to transfer a value between two different components in React

I have 2 components. First: component.ts @Component({ selector: "ns-app", templateUrl: "app.component.html", }) export class AppComponent implements OnInit { myid: any; myappurl: any; constructor(private router: Router, private auth: ...

Using for loops in Vue.js to dynamically generate HTML elements

I have a JSON object passed into an EJS template, and I want to achieve the same table structure in VUE.js. However, it seems like v-for in Vue only works with li tags. Is there a way to create a similar loop in VUE that generates HTML elements like show ...

The compatibility between V-model and TinyMCE is unreliable

I've been working on integrating Vuejs and TinyMCE, using the @tinymce/tinymce-vue package for the Vue integration. I followed all the instructions and everything seems to be functioning properly - I can write, insert images... everything except for t ...

What is causing checkboxes to malfunction within a form?

In my project, I have an array of objects representing pets: pets = [{key: 'dog', isChecked: true}, {key: 'hamster', isChecked: false}, {key: 'cat', isChecked: false}]; I want to display these objects as checkboxes. Here is ...

Using a dropdown list to filter values in a table with Angular ngBootstrap

Seeking assistance with filtering table values based on the selected filter. I plan to utilize this ngbDropdown as my filter. If I choose company A, only entries related to company A will be displayed in the table. I am unsure about how to connect the f ...

The sidebar stays fixed in place and doesn't adapt to varying screen resolutions

Check out my website at . I have a fixed, blue sidebar on the left side of the page to ensure its content is always visible. However, I'm facing an issue with smaller resolutions like 1024x768 where some bottom content is cut off. How can I adjust the ...

Retrieving raw HTML content using Angular's http.get() method

Currently working on a project where I need to load data dynamically from a website without the use of an API. Is there a way in Angular to utilize http.get in order to fetch the entire website as raw HTML, allowing me to extract specific information? Any ...