Here are the steps to iterate through two arrays and compare them in Angular 2 when the same checkbox is checked

I have two arrays: one containing a list of all office locations, and another with user-selected offices. My goal is to display all the office locations and have the checkboxes checked if they match those in the selected list. Here is how I accomplished this:
Code

<div *ngFor="let item of officeLIST">
  <div *ngFor="let officeDATA of allOffice.office">
    <div *ngIf="item.office_id == officeDATA.office_id">
      <input #officeArray type="checkbox" id="officeArray" name="officeArray" class="form-control" value="{{item.officename}}"
        checked> {{(item.officename == "" ? "--No data--" : item.officename)}}
    </div>
    <div *ngIf="item.office_id != officeDATA.office_id">
      <input #officeArray type="checkbox" id="officeArray" name="officeArray" class="form-control" value="{{item.officename}}">      {{(item.officename == "" ? "--No data--" : item.officename)}}
    </div>
  </div>
</div>

Result:https://i.sstatic.net/v3cjr.png

My officeLIST

this.officeLIST = [
  { "office_id": "1", "officename": "Sun Dept" },
  { "office_id": "2", "officename": "Moon" },
  { "office_id": "3", "officename": "Stars" }
]

allOffice.office array

"office": [
    {
      "office_id": "1",
      "officename": "Sun Dept"
    },
    {
      "office_id": "2",
      "officename": "Moon Dept"
    }
  ]

Answer №1

Try implementing this solution, it has worked perfectly for me. I have included all the necessary steps in the constructor. If you prefer to have it in a method, just place the code block inside the constructor.

This is my TypeScript file:

  officeLIST: Array<any> = [
    { "office_id": "1", "officename": "Sun Dept" },
    { "office_id": "2", "officename": "Moon" },
    { "office_id": "3", "officename": "Stars" }
  ];


  office: Array<any> = [
    {
      "office_id": "1",
      "officename": "Sun Dept"
    },
    {
      "office_id": "2",
      "officename": "Moon Dept"
    }
  ];
  newArray: Array<any> = [];
  constructor() {
    for (var i = 0; i < this.officeLIST.length; i++) {

      var ismatch = false; // we haven't found it yet

      for (var j = 0; j < this.office.length; j++) {

        if (this.officeLIST[i].office_id == this.office[j].office_id) {
          // we have found this.officeLIST[i]] in this.office, so we can stop searching
          ismatch = true;
          this.officeLIST[i].checked = true;//  checkbox status true
          this.newArray.push(this.officeLIST[i]);
          break;
        }//End if
        // if we never find this.officeLIST[i].office_id in this.office, the for loop will simply end,
        // and ismatch will remain false
      }
      // add this.officeLIST[i] to newArray only if we didn't find a match.
      if (!ismatch) {
        this.officeLIST[i].checked = false;//  checkbox status false
        this.newArray.push(this.officeLIST[i]);
      } //End if
    }
    console.log(this.newArray);

  }

This is my HTML:

<div *ngFor="let item of newArray">
  <input type="checkbox" [checked]="item.checked"> {{item.officename}}
</div>

Answer №2

The user-selected array will contain the IDs of the checkboxes that have been selected by the user. For example, if the user selected Sun Dept and Moon, the userSelectedArray would be ["1", "2"].

this.userSelectedArray = ["1","2"];

<div *ngFor="let item of officeLIST">
      <input type="checkbox" [attr.checked]="userSelectedArray.indexOf(item.office_id) !== -1 ? true : false">
    </div>

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

Using typescript, we can pass a generic class as a parameter to a function

Currently, I am faced with the challenge of passing a class reference as a function parameter, and then calling a static method on this particular class. Additionally, there is a possibility that in the future, I may need to instantiate the class and inclu ...

Having trouble triggering an alert() after a successful post to the database

As I delve into the realm of backend development, I find myself facing what seems like a simple puzzle that I just can't solve. My goal is to create a basic CRUD app to enhance my skills, so I decided to build a blog platform that could eventually be ...

Error in Angular 16.2.0: Signal TypeError <mySignal> cannot be executed as a function

I have a service that has a signal containing a list of Customers (interface). Whenever I call a method to retrieve the signal content, I encounter an issue: ERROR TypeError: this.customers is not a function at Object.upsertCustomer [as next] Here is th ...

There was an error when trying to read the file '.angular-cli.json'. Please double-check to ensure that the file contains valid JSON format. The error message indicates an unexpected

After installing npm install ng-file-upload, I added the ng-file-upload package to my project. Unfortunately, I am encountering errors in my project now. D:\web\ng4fbbootstrap\node_modules\@angular\cli\models\config&bsol ...

Is it possible to transfer parameters from one page to another page using the pop method in Ionic 2?

Is it possible to pass parameters from one page to another during a push operation, but how can this be done during a pop operation? showfilter(){ this.navCtrl.push(FilterPage,{ fulldetail : this.selectedarea }); } Can you explain how ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Angular micro front-end powered by module federation

I am interested in developing micro front-end applications using module federation. I have successfully implemented it following the guidelines provided on this informative page. However, I am facing a challenge where I want each project to have its own u ...

Encountering an Issue in Angular 4 When Trying to Present JSON Data in a Table

Having trouble displaying the content of the JSON below using Angular 4 and Typescript: Display timed_out and max_score in a text box Display CV/JOB in a table. Any suggestions? { "took": 56, "timed_out": false, "_shards": { "total": 18 ...

Compiling the project using ng build without requiring the download of node

Hey there! Is there a method to execute the ng cli command (ng build --prod) without having to download the npm packages repeatedly? The production build process is becoming very sluggish due to this issue. I am curious to know if there is a way to avoid ...

Typescript: Defining the correct return type for resolved parameters in promises

Exploring the world of TypeScript, I recently attempted to convert some basic JavaScript promise samples into TypeScript promises. While working on this conversion process, I encountered an issue that has left me puzzled and unable to find a solution even ...

JavaScript Arrays and Their Mysterious Undefined Elements

Creating a basic HTML document with a JavaScript script can be quite simple. ... <script type = "text/javascript"> src = "xxx.js"></script> ... <body> <ul id ="pics"> <li><a href="A.jpg">A</a></li> ...

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

Secure your React TypeScript applications with GraphQL authentication

When users try to log in on my website, I need to verify their authentication using data from a GraphQL API. I referred to this tutorial for guidance: https://www.apollographql.com/docs/react/networking/authentication/ In my GraphQL playground, I execute ...

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

What is the process for transforming an exported function into a function type?

When writing Express middleware, I am facing challenges in deciding how to properly typecast my functions. For instance, when working on an error handler: export function errorHandler(err, req, res, next) { ... } TypeScript correctly points out that th ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Explore how Angular can display the highlights of deepDiff results in JSON format!

I am utilizing deepDiff to display the variances between two JSON objects in a structured manner, which is working well so far. However, I am aiming to highlight these disparities within the parsed JSON contents, but it's not quite effective. How can ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

The input of type 'Observable<true | Promise<boolean>>' cannot be assigned to the output of type 'boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree>'

I'm currently using a Guard with a canActivate method: canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.fi ...