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

The Angular 2 Final Release is encountering an issue where it is unable to locate the module name with the

Recently, I made the transition to Angular 2 Final Release from RC 4 and encountered an issue with an error message cannot find name 'module' in my code: @Component({ selector: 'dashboard', moduleId: module.id, templateUrl: ...

Resolve the result of the HttpComponent within the Service component

Consider this example involving HttpClient: In Service configData: string[]; fetchData(): Observable<string[]> { return this.http.get<string[]>('./assets/config.json'); } getConfigValue(key: string): string { if ...

Unable to retrieve data from all clients in Angular / Nest.js using socket.io

I have been experimenting with socket io in a small project using angular and nestjs. However, I am facing an issue where the data is only being received on the same client that it was sent from. The other clients are not updating their components after e ...

How come the path alias I defined is not being recognized?

Summary: I am encountering error TS2307 while trying to import a file using an alias path configured in tsconfig.json, despite believing the path is correct. The structure of directories in my Angular/nx/TypeScript project appears as follows: project |- ...

Command to update a document in AWS DynamoDB using the Document Client

While attempting to utilize the UpdateCommand feature within the AWS DynamoDB documentation, I encountered various challenges due to its lack of detailed explanation and difficulty in implementation. My aim was to employ the update command to seamlessly t ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

What methods does Angular use to differentiate between router-outlet tags that are located in various components?

Within the app.component.html, we include a < router-outlet > tag that dynamically loads other modules, components, and views. However, if we have a second component (imported in a different module) with its own < router-outlet > How does Ang ...

After subscribing, creating the form results in receiving an error message that says "formgroup instance expected."

I am currently working on a project using Angular 6 to create a web page that includes a form with a dropdown menu for selecting projects. The dropdown menu is populated by data fetched from a REST API call. Surprisingly, everything works perfectly when I ...

Encountering issues accessing / Error within MEAN stack application

I recently completed the Heroku tutorial, which you can find here. I followed all the steps but did not deploy to the Heroku server and instead worked on my localhost. However, when I tried to access my application using localhost port 8080, I encountered ...

Incorporating real-time checked checkbox values into a running list

When displaying a list of preferences as checkboxes, I encountered an issue with the binding part. I am trying to capture the IDs of the checkboxes that are checked. Here is my attempt, which unfortunately does not work: <div class="checkbox" *ngFor="l ...

Utilizing Nginx to route to various locations with distinct root paths in an Angular server-side rendered build

My website is up and running on the server, hosted at http://example.com. It was built using Angular and I deployed the dist folder containing the code to /opt/example_web/dist/browser on the server. The site is redirecting and loading successfully. I als ...

What is the best way to utilize nested components in Angular 2's latest stable release?

When using previous RC releases, we were able to use the directive tag for nested components. However, in the final release of Angular 2, the directive tag has been removed from components. So now, what is the best approach for placing one component inside ...

Encountering the error message "Receiving 'Multiple CORS header 'Access-Control-Allow-Origin' not allowed' while accessing my Laravel API from Angular"

After successfully developing an API with Laravel that functioned perfectly with Postman, I am now working on its front-end using Angular. However, I keep encountering this error every time I send a request to the API: Cross-Origin Request Blocked: The Sa ...

Tips on mocking an ngrx selector within a component

Within a component, we utilize an ngrx selector to access various segments of the state. public isListLoading$ = this.store.select(fromStore.getLoading); public users$ = this.store.select(fromStore.getUsers); The fromStore.method is formed using the ngrx ...

What is the best way to take any constructor type and transform it into a function type that can take the same arguments?

In the code snippet below, a class is created with a constructor that takes an argument of a generic type. This argument determines the type of the parameter received by the second argument. In this case, the first parameter sets the callback function&apos ...

Find the combined key names in an object where the values can be accessed by index

I am currently working on creating a function called indexByProp, which will only allow the selection of props to index by if they are strings, numbers, or symbols. This particular issue is related to https://github.com/microsoft/TypeScript/issues/33521. ...

The Angular component fails to refresh after removing an image

After deleting an image, I have been struggling to find a way to update my component instantly without having to refresh the page. Despite trying various methods like using ChangeDetectorRef, I haven't been successful. Any advice on how to achieve thi ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

Mapping the preselected values of multiple input fields into an array in Angular 6: A step-by-step guide

When submitting a form with input fields, I need to capture the selected values into an array format like {"userid":1,"newstatus":[1],"mygroup":[1,2,3]}. I attempted using ngmodel but encountered issues. Below is the code snippet: home.component.html & ...

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...