Ensure to verify within the ngOnInit function whether the checkbox has been selected

Hi everyone, I'm currently facing a situation where I have a list of checkboxes on one screen. When I select some checkboxes, they move to another screen and remain selected there. However, the issue is that when I try to use a button on the second screen, it doesn't recognize them as selected until I click on them again. Does anyone know how I can capture the selection information so that I can implement the necessary methods? Alternatively, if the checkboxes generated using ngFor don't have an ID, how can I display them without requiring the user to mark them first before invoking the method?

Answer №1

component.html

  <form [formGroup]="form" >
  <p><b>Interactive Checkbox Example</b></p>

   <ul formArrayName="fruits">

     <li [formGroupName]="i" *ngFor="let item of form.controls?.fruits?.controls; let i = index">
       <input type="checkbox" formControlName="checked" />  {{fruits[i].name}}
     </li>

    </ul>
</form>

component.ts

fruits:Array<any> = [
   { name: '🍓', checked: true },
   { name: '🍌', checked: false }
]

ngOnInit(): void {
  // create reactive form structure
  this.form = new FormGroup({
    fruits: new FormArray([]),
  });
  // assign existing values to form control
  this._patchValues();
}

private _patchValues(): void {
  const formArray = this.form.get('fruits') as FormArray;
  this.fruits.forEach((fruit) => {
    formArray.push(
      new FormGroup({
        name: new FormControl(fruit.name),
        checked: new FormControl(fruit.checked),
      })
    );
  });
}

Answer №2

Just starting out in Angular, but I managed to overcome my challenges by utilizing @Output and EventEmitter. Apologies for any lack of clarity on my part.

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

Is it possible to set up a PHP variable within a JavaScript function?

In the code snippet above, we have a JavaScript function that is used for validation. I am looking to set a PHP variable within the else statement. function validate() { if(document.loginForm.vuser_login.value==""){ alert("Login Name name ca ...

Exploring the synergies of Next.js and Node.js thread pooling

In my current project, I am utilizing nextJS with NodeJS and looking to implement child processes or workers. The code provided by NextJS itself is functioning perfectly. The relevant code snippets: NextJS with NodeJS Another resource I referred to: Nex ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

I set up a website where every page had a consistent header using the HTML tag <head> <!--#include file="header.shtml"--> </head>, but out of nowhere, the Bootstrap functionality

I created a website with a common header that is included on all pages, but suddenly Bootstrap stopped working. What should I do now? Below is the code that was working fine previously but suddenly stopped yesterday: I have tried various solutions like r ...

ng-bind-html not functioning properly within my situation

Utilizing the ngBindHtml directive in AngularJS to dynamically append HTML, but encountering issues with some area tag attributes not being properly added within the div. As a result, the onclick event in the area tag is not functioning as expected. When ...

Trouble with displaying map in Angular 8 Accordion

Working on an Angular project utilizing Bootstrap accordion, I encountered an issue where the openstreet map fails to display when the panel is clicked. Check out the project here Interestingly, if I modify the behavior to always show the panel by adding ...

What is the best way to retrieve the dimensions of a custom pop-up window from the user?

Currently, I am in the process of developing a website that allows users to input width and height parameters within an HTML file. The idea is to use JavaScript to take these user inputs and generate a pop-up window of a custom size based on the values pro ...

What is the best way to maintain the correct 'this' context for a function that is outside of the Vue

I'm struggling with my Vue component and encountering some errors. <script lang="ts"> import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, va ...

The onChange function in React is not behaving as I anticipated

Consider the following data structure for tables: an array of objects containing nested objects: [ { "1": { "1": "Item s ", "2": "Manufacturer ", "3" ...

Tips on moving the inner rectangle within the outer rectangle

I am currently trying to center the innermost shape (the red shape) along the X-axis to the middle of the outermost shape (the black shape), while ensuring that the red shape remains within its direct parent, which is the blue shape. For instance, centeri ...

Unlock the full potential of p-checkbox with PrimeNG's trueValue and falseValue feature

I've been attempting to incorporate a p-checkbox in Angular8 with true and false values as strings instead of booleans. So I tested the following code: <p-checkbox [(ngModel)]="mycheckbox" name="mycheckbox" inputId="mycheck ...

Determining the scroll position of a JQuery Mobile collapsible set upon expansion

I am utilizing jQueryMobile (v1.4.0) collapsible set / accordions to showcase a list of elements along with their content, which can be seen in this jsFiddle. <div id="List" data-role="collapsible-set"> <div data-role="collapsible" data-conte ...

Utilize Haxe Macros to swap out the term "function" with "async function."

When I convert haxe to JavaScript, I need to make its methods asynchronous. Here is the original Haxe code: @:expose class Main implements IAsync { static function main() { trace("test"); } static function testAwait() { ...

Why doesn't the Angular router events Observable have an unsubscribe method available?

Within my Angular component's ngOnInit lifecycle method, I am subscribing to the Router events like this: this.router.events.subscribe( event => { if (event instanceof NavigationEnd) this.clearMessages(); } ); Typically, when dealing with ...

Solving Checkbox Change Event Issue in Angular

I'm having difficulty testing the checkbox-change event for a particular component. Here is the code for the component that needs to be tested: import { Component, Output, EventEmitter } from '@angular/core'; @Component({ selector: &a ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Struggling with efficiently sorting data within a list on Angular.js

Can someone assist me with an issue I am having while filtering data from a list using Angular.js? I am also utilizing angularUtils.directives.dirPagination for paginating the list. Below is my code explanation: <input class="form-control" placeholder= ...

Implementing a jQuery click functionality on elements generated dynamically

I have a challenge where I need to attach a click event to buttons associated with each form in a dynamically created list of forms. Each form contains delete, edit, save, and cancel buttons. Initially, the save and cancel buttons are hidden. When the edit ...

Enhance the way UV coordinates are generated for rotated triangles/faces within THREE.js

While researching how to map a square texture onto n-sided polyhedrons using a convex hull generator in THREE.js, I found that existing solutions did not fully address my issue. The challenge was to ensure that the texture was not distorted and appeared co ...