Tips on pairing elements from a ngFor processed list with another list using ngIf

If we have a list such as the one shown below:

elements = [
  { id: 1,
    name: "one"
  },
  { id: 3,
    name: "three"
  },
  { id: 5,
    name: "five"
  },
  { id: 6,
    name: "six"
  },
];

lists = [
  { id: 5,
    name: "five"
  },
  {
    id: 9,
    name: "nine"
  },
];

I am trying to make sure that only items with matching ids from 'elements' and 'lists' are displayed when using ngFor and ngIf directives. However, I am unsure of the correct syntax to achieve this.

<div *ngFor="let element of elements">
  <p *ngIf = "lists.some(list => list.id === element.id)">
    {{ element.name }}
  </p>
</div>

Answer №1

If you want to determine if a specific item exists in an array, you can utilize the Array#some method.

<p *ngIf="lists.some(e => e.id === item.id)">

The some method will return true when it finds an element in the lists array with the same id value as the item being checked.

Answer №2

If you want to streamline the filtering process for your items, consider implementing a custom pipe within the *ngFor directive.

Here is an example of how you can achieve this:

<div *ngFor="let item of items | customFilter:lists">
  <p>
    {{ item.name }}
  <p>
<div>

Now, let's create the custom pipe:

@Pipe({name: 'customFilter'})
export class CustomFilterPipe implements PipeTransform {
  transform(items: object[], lists: object[]): object[] {
    return items.filter(item => {
      lists.some(e => e.id === item.id)
    });
  }
}

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 functionality of Ajax loading content will fail when the link is already loaded

I am currently using an ajax script that dynamically replaces the content of #main with the contents of a loaded page based on the clicked link. For example, clicking on rddd would replace #main with the content of about.php. However, I encountered an is ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

I am encountering undefined values when utilizing momentjs within Angular

My project is utilizing angular and momentJS, with the addition of the angular-moment library. You can find my current progress in this fiddle However, I am encountering an error when trying to use moment in a controller method: TypeError: undefined is n ...

What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole. The issue arises when the UserRole is also retrieved in the query below: async getUser ...

Steps for referencing an autogenerated id in a Firestore collection

I need assistance updating a 'progress' field in a document with an autogenerated ID (using Firestore) every time the progress button is clicked. https://i.stack.imgur.com/hZieN.png Despite my attempts, nothing seems to work. Here is the method ...

While developing my project in NextJS, I encountered a frustrating issue where the build process would fail consistently, even though the development environment ran smoothly. The

Hello everyone, I'm a beginner posting here for the first time. I am still getting the hang of React and JavaScript in general, and currently working on a project in NextJS. It's interesting to note that my project runs smoothly when I use next d ...

Incorporating marker tags to different sections of text within a contenteditable div

The main objective of this feature is to enable users to select placeholders within message templates (variable names enclosed in %). Inspired by Dribbble The API provides strings in the following format: "Hello %First_Name% %Middle_Name% %Last_Name% ...

Django DRF functions properly, however it returns an error when sending a response to an AJAX request

Successfully implemented an AJAX request using PUT in DRF. All functionalities are functioning correctly except for the error callback being triggered: DRF section: class ProductDataViewSet(viewsets.ViewSet): authentication_classes = [SessionAuthentic ...

Learn how to retrieve data by clicking on the previous and next buttons in FullCalendar using Vue.js

Seeking guidance on retrieving calendar data from the database for my Vue frontend, I have incorporated the fullcalendar API. Successfully able to retrieve data for the current week, however facing challenges when attempting to fetch data for the previous ...

Error Encountered While Creating a Polygon Wallet on Fireblocks

After following the instructions from Fireblocks Docs, I successfully created a default wallet named "BTC_TEST" like this: enter image description here. However, when attempting to create a Matic wallet, I encountered an Axios Error. Despite Matic being a ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

A guide to generating dynamic table headers using JSON in React

Looking to create a dynamic table with columns/headers in React based on a JSON array of objects. The data: example = [ { id: 0, city: 'New York', }, { id: 1, city: 'Paris', }, ] Currently, I'm iterating ...

Is it possible for Angular to handle multiple routes for one path?

To create a landing page for anonymous users and an inbox for authenticated users without relying on manual navigation or path changes, I attempted to set up multiple components associated with the root path. However, my routing block did not work as plann ...

Requesting JSON data from an API with cross-origin - "You might require a suitable loader to manage this particular file format."

I am currently attempting to retrieve JSON data from the Genius API using Webpack and Axios in a web browser. This involves a Cross-Origin Request, which can sometimes be a bit challenging. Initially, I encountered the following error message: Failed to ...

"Seeking a more flexible JSON parser that allows for greater

I am in need of passing various strings that are formatted as json to a json parser. The issue is that jQuery.parseJSON() and JSON.parse() strictly support only a specific json format: If a malformed JSON string is passed, an exception may be thrown. For ...

Loop through each object in an array and verify if the value matches a specific criteria in Javascript

Explore the common issues related to object iteration and queries outlined below. Presented here is a list of objects (used for managing a connection form): const connectionData = { mail: { value: false, isRequired: true }, password: { v ...

console displaying indentation problems with laravel and vue

I am currently utilizing Vue within Laravel and encountering a multitude of indentation errors in the console. https://i.sstatic.net/sfRec.png Here is an excerpt from my package.json file: "private": true, "scripts": { "clean": "rimraf public/buil ...

Activate the jquery function when the content of the <ul> element changes

Looking for a way to trigger a jQuery function when the content of an unordered list (ul) changes. Check out the code I've written below: JavaScript jQuery(document).ready(function($) { $('.ProductList').on('change', fun ...

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

Implementing a splash screen upon selecting the second exit option

Check out the code snippet here: https://jsfiddle.net/wust7gdy/ Once the curtain is raised, the exit button will appear. How can I introduce a splash screen after clicking the 2nd exit button? Currently, there is a splash screen that appears after click ...