Exploring the process of selecting checkboxes in Angular 6

I'm currently learning Angular 6 and I have a requirement to mark checkboxes based on specific IDs from two arrays:

 this.skillArray = [
        {ID: 1, name: "Diving"},
        {ID: 2, name: "Firefighting"},
        {ID: 3, name: "Treatment"},
        {ID: 4, name: "Mechanics"},
        {ID: 5, name: "Floods"},
        {ID: 6, name: "Drilling"},
        {ID: 7, name: "Electricity"},
        {ID: 8, name: "Celebrations"},
        {ID: 9, name: "Events"},
        {ID: 10, name: "Prayer"}
    ]

  var splitstr = ["9", "7"];

My goal is to check the checkbox for IDs 9 & 7. I managed to accomplish this and also implemented an onchange function to post the value. However, the issue I encountered was that the checked values were not getting pushed to the array. How can I resolve this?

<form [formGroup]="myForm">
<div *ngFor="let data of skillsArray">
<p><input type="checkbox" [checked]="inputChecked(data.ID)" (change)="onChange(data.ID, $event.target.checked)"> {{data.name}}</p>
</div>

</form>

inputChecked(id:any) {
    let checked = false;
    console.log(this.splitstr);
    for (let l = 0; l <this.splitstr.length; l++) {
    let temp = this.splitstr[l];
    if (temp == id) {
    checked = true;
  }
}
return checked;
}


onChange(value: any, isChecked: boolean) {
  const skillFormArray = <FormArray>this.myForm.controls.VFields;
  if (isChecked) {
  skillFormArray.push(new FormControl(value));
  }
  else
  {
  let index = skillFormArray.controls.findIndex(x => x.value == value)
  skillFormArray.removeAt(index);
}

}

Answer №1

Here is a suggestion for you to consider:

Your component code:

activeEls = [];
neededValues = [1,3];

changeStatus(car: Cars){
  car.checked = !car.checked;
  if(car.checked){
    this.activeEls.filter(function(value, index, arr){

      return value == car.id;

    });
  }
else{
    this.activeEls.splice(this.activeEls.indexOf(car.id),1);
  }
  console.log(car.id, " status= ", car.checked);
}

ifOneAndThreeIsActive(){
for (let ca of this.cars){
if(this.activeEls.includes(ca.id))
  continue;
if(ca.checked)
  this.activeEls.push(ca.id);
}
let concur = 0;
for(let j = 0, l1 =  this.activeEls.length; j < l1; j++){
if(this.neededValues.length <= j && !this.activeEls.includes(this.neededValues[j])){
  continue;
}
++concur;
if(concur == this.neededValues.length && this.activeEls.length === this.neededValues.length)
  console.log(this.neededValues, 'correct');
console.log(concur);
}
console.log(this.activeEls);

}

Your HTML file:

<ul class="list-group">
  <li class="list-group-item" *ngFor="let car of cars">     
    <input type="checkbox" (click)="changeStatus(car)" [checked]="car.checked">
  </li>
</ul>
  <button class="btn btn-info" (click)="ifOneAndThreeIsActive()">Check if 1 & 3 are active</button>

<button class="btn btn-info" (click)="pushNum(2)">push

If you only want this solution to work when 1&3 are selected, you will need to adjust the numbers in the example.

Does this solution fit your needs?

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

Generating Angular components dynamically in batch

I have a collection of diverse data objects: const arr = [ {type: 'CustomA', id: 1, label: 'foo'}, {type: 'CustomB', src: './images/some.jpg'} {type: 'CustomX', firstName: 'Bob', secondNa ...

The Angular template loads and renders even before the dynamic data is fetched

I'm encountering a frustrating issue where the page loads before the data is retrieved. When I log the names in $(document).ready(), everything appears correct without any errors in the console. However, the displayed html remains empty and only shows ...

Learn how to navigate to a different page in Angular 4 using a button click

I'm trying to set up a button in my home.component.html page that will redirect the URL to a new page when clicked. My expectation is that clicking the button will change the current URL from http://localhost:24282/home to http://localhost:24282/mast ...

What is the best way to test a callback function of a React component that is encapsulated with withRouter()?

In my Jest and Enzyme testing of a TypeScript-written React project, I have a component wrapped in a React-Router router. Here's a snippet of the code: import { SomeButton } from './someButton'; import { RouteComponentProps, withRouter } fr ...

The Jasmine test is having trouble locating the imported variable

In my Angular project, I have a class set up as follows: import { USERS } from "./data/users"; // imports an Array of Objects export class User { constructor(name: string) { const user = USERS.find(e => e.name === name); } ... } Every ...

Encountering build:web failure within npm script due to TypeScript

Our project is utilizing the expo-cli as a local dependency in order to execute build:web from an npm script without requiring the global installation of expo-cli. However, when we run npm run build:web, we encounter the following exception. To isolate th ...

Strategies for effectively choosing this specific entity from the repository

Is it possible to choose the right entity when crafting a repository method using typeorm? I'm facing an issue where I need to select the password property specifically from the Admin entity, however, the "this" keyword selects the Repository instead ...

Please ensure that the table contains all the records corresponding to the respective days

I am struggling with figuring out how to display a record of classes in my table view. The UX prototype I need to follow is shown https://i.stack.imgur.com/CISYn.png (the days of the week are in Portuguese: horario = time, segunda = Monday, terça = Tuesda ...

Are you looking to denormalize your ngrx store and configure selectors?

I am currently dealing with a complex data structure in an ngrx project. It consists of nested parent objects with multiple levels of child objects, which are normalized on the server side. Here is an overview of my store's layout: rootObjs: { le ...

Arrange a JavaScript map based on its values and ensure that a specific field index remains at the top position

I'm sure this question may seem simple to some, but as a JavaScript novice, I couldn't find the answer myself. Here is the code snippet I'm working with: Let map = new Map<String,String> map.set('0', select) map.set('1&a ...

Transform the MUI Typescript Autocomplete component to output singular values of a specific property rather than a complete object

When utilizing MUI Autocomplete, the generic value specified in onChange / value is determined by the interface of the object set in the options property. For instance, consider an autocomplete with the following setup: <Autocomplete options={top ...

Ensuring Data Consistency: Using TypeScript to Strongly Type Arrays with Mixed Variable Types

I have a JSON array that may contain objects of two types, defined by IPerson and ICompany. [ { "Name" : "Bob", "Age" : 50, "Address": "New Jersey"}, { "Name" : "AB ...

"Overcoming obstacles in managing the global state of a TypeScript preact app with React/Next signals

Hello, I recently attempted to implement a global app state in Preact following the instructions provided in this documentation. However, I kept encountering errors as this is my first time using useContext and I suspect that my configuration might be inco ...

Ensure all promises are resolved inside of for loops before moving on to the next

Within my angular 11 component, I have a process that iterates through elements on a page and converts them from HTML to canvas to images, which are then appended to a form. The problem I am encountering is that the promise always resolves after the ' ...

Issue with the rendering of Navigation Bar in Angular 4 Bootstrap alpha

I am currently working on integrating Bootstrap 4 into my Angular 4 application by following a tutorial. However, I have encountered an issue with the navigation bar not functioning correctly. https://i.sstatic.net/92phM.png After taking the necessary st ...

Encountered an issue locating the stylesheet file 'css/style.css' that is supposed to be linked from the template. This error occurred when trying to integrate Bootstrap with Angular

<link rel="stylesheet" href="plugins/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="plugins/owl-carousel/owl.carousel.css"> <link rel="stylesheet" href="plugins/magnific-pop ...

Combining types with additional features

Is it possible to configure the TypeScript compiler to generate an error when a function is called with an argument that can belong to both cases in a union type? For example: interface Name { name: string } interface Email { email: string } type ...

Learn how to retrieve images from the web API at 'https://jsonplaceholder.typicode.com/photos' and showcase them on a webpage using Angular10

Using the API "https://jsonplaceholder.typicode.com/photos", I have access to 5 properties: albumId: 1 id: 1 thumbnailUrl: "https://via.placeholder.com/150/92c952" title: "accusamus beatae ad facilis cum similique qui sunt" url: "https://via.placeh ...

Creating a custom extended version of Angular2 Http does not automatically provide injection of services

I'm struggling to understand this issue. I've created a custom class that extends Angular's Http class. import { Injectable } from '@angular/core'; { Http, ConnectionBackend, RequestOptions, RequestOptionsArgs, ...

Resolving TypeScript errors when using the Mongoose $push method

It appears that a recent package upgrade involving mongoose or @types/mongoose is now triggering new typescript errors related to mongoose $push, $pull, $addToSet, and $each operators. For instance: await User.findByIdAndUpdate(request.user._id, { $ ...