Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array.

component.ts

public checkDevice(obj) {
    if (obj == null || obj == '' || obj == '-1') {
      return false;
    } else {
      return true;
    }
}

component.html

<div class="float-left" *ngIf="checkDevice(obj.device_token) == true">
   <i class="fa fa-icon" aria-hidden="true"></i>
</div>

Edit the PHP script responsible for database queries.

$users = array();
if ($results = $dbh->runQuery($sql)) {

  foreach ($results as $key=>$row){
    $users[$row['user_id']][] = array('user_id'=>$row['user_id'],
      'user_token' => $row['utoken'],
      'device_token' => $row['device'],
      'group_name' => $row['group_name']);
  }
}

Answer №1

If you are looking to test for the existence of a specific object property, consider using the following approach:

<div class="float-left" *ngIf="obj.device_token">
  <i class="fa fa-icon" aria-hidden="true"></i>
</div>

If you need to determine how many times a device object appears in an array, you can use this solution:

getDeviceOccurrence(deviceArray: Array<object>, device: object): number {
  return deviceArray.reduce((accumulator: number, currentValue: object) => {
    if (_.isEqual(currentValue, device)) {
      return accumulator = accumulator + 1;
    }
    return accumulator;
  }, 0);
}

Key points about this implementation:

  • For comparing objects, it's recommended to import and utilize lodash's isEqual function.
  • The function accepts two parameters - an array containing devices and the specific device. It returns the count of occurrences of the device within the array.
  • This method employs the use of reduce function.

How to use it in your template:

<span>{{ getDeviceOccurrence(devices, device) }}</span>

Answer №2

I believe you have the capability to create this script as well.

<div class="float-left" *ngIf="obj.device_token">
   <i class="fa fa-icon" aria-hidden="true"></i>
</div>

Answer №3

It's best practice to avoid using functions for data-binding in your HTML as it can impact performance, since the function will be called every time to check.

If you already have an array of devices and are iterating through them using ngFor, here are some steps I recommend:

  • Create a filtered array where you remove all devices with null or empty tokens
  • Use this filtered array for binding with your ngFor (ensuring that the token is loaded)

By doing this, you address two issues:

  • You improve performance by avoiding binding functions with *ngIf
  • You resolve the issue of incorrect item count, as you now have a new array containing only items with tokens

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 to compare and filter items from two arrays using TypeScript

I am looking to filter out certain elements from an array in TypeScript Original Array: [ {"Id":"3","DisplayName":"Fax"}, {"Id":"1","DisplayName":"Home"}, {"Id":&quo ...

Communicating from JQuery-UI to Angular 6 using callbacks

I incorporated the jQuery-UI MonthPicker into my Angular 6 application, and now I am looking to trigger an Angular action whenever the date changes: ngOnInit() { $(document).ready(function() { $('#myMonthPicker').MonthPicker( ...

Mastering checkbox selection in Angular reactive formsLearn how to effortlessly manage the checked status of

I am struggling with setting the checked status of a checkbox control within an Angular reactive form. My goal is to change the value based on the checked status, but it seems like the value is controlling the status instead. For instance, I want the for ...

Looking for a solution to resolve the issue "ERROR TypeError: Cannot set property 'id' of undefined"?

Whenever I attempt to call getHistoryData() from the HTML, an error message "ERROR TypeError: Cannot set property 'id' of undefined" appears. export class Data { id : string ; fromTime : any ; toTime : any ; deviceType : string ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

You need to provide 1 type argument(s) for the Generic type ModuleWithProviders<T> in Angular 10 Swagger Codegen

Currently, I am generating Codegen proxies using . Upon implementing this in Angular 10, I encountered the following error. How can this issue be resolved? The error message reads: 'Generic type 'ModuleWithProviders' requires 1 type argume ...

Why does routing function correctly in a browser with AngularUI Router and Ionic, but not in Ionic View?

My Ionic App runs smoothly in the browser when using ionic serve. However, I encounter issues with routing when running the app in Ionic View (view.ionic.io) after uploading it with ionic upload. The index.html loads but nothing within <div ui-view=""& ...

Struggling to access localhost in the browser despite receiving confirmation in the terminal that it is listening on localhost

After successfully creating a new app using angular cli, I launched the server and received the message in the terminal that it is listening on localhost:4200. Please see the image at this . However, when I try to access localhost, I receive an error mess ...

Should one prioritize learning TypeScript over diving into Angular2?

Should I prioritize learning TypeScript before diving into AngularJS 2? ...

Angular Material Table displaying real-time information

Recently, I've delved into Angular and have been experimenting with creating a dynamic table to showcase data. Currently, I have managed to get it partially working with static data. I drew inspiration from this particular example: https://stackblit ...

Why is my input field value not getting set by Angular's patchValue function

I've been attempting to populate an input field using the form group with patchValue(), but for some reason, the input remains empty. Here's a snippet of my code... component.html <form [formGroup]="createStoreForm" (ngSubmit)="createStor ...

Angular 2: Accessing the parent component from the output

I am a beginner in Angular 2 and I've been exploring ways to access the value of an attribute from a parent component using the @Output feature. Below is the code snippet: ParentPage.ts export class ParentPage { name: string; constructor(){ ...

Forwarding routes with Angular Router

My server has specific mappings for different URLs: / serves an Angular application with routing capabilities /admin serves a Django control panel for staff database updates /api and /api/... serve REST endpoints to handle queries and return JSON data I ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

Generating instances of classes using variables in Typescript

Are there methods to modify the below piece of code in order for it to be compatible with Typescript? public shops: string[] = [ "AShop", "BShop", "CShop", ]; this.shops.forEach((shop, index) => { let instance = new window[shop](index ...

Tips for ensuring radiobuttons are defaulted to unchecked within a shared form group in Angular 2 and beyond

The radio buttons are linked to data from the database (Web-API). Below are my complete code snippets: component.html <!-- list of Questions --> <div formArrayName="questions"> <!-- <div *ngFor="let que of Questions; let ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Setting up the environment variable for ApolloClient to be utilized in server-side rendering for continuous integration/continuous deployment involves following a specific

My apolloClient is configured as follows: /** * Initializes an ApolloClient instance. For configuration values refer to the following page * https://www.apollographql.com/docs/react/api/core/ApolloClient/#the-apolloclient-constructor * * @returns Apoll ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...