Display the initial occurrence from the *ngIf statement

Is there a way to display only the first match from the *ngIf?

I am currently using an object loop with *ngFor, where I have multiple items with the same Id but different dates. I need to filter and display only the item with the most recent date and avoid duplicates based on the objectId.

Answer №1

To implement this functionality in an HTML file:

<div *ngFor="let item of list">
  <div *ngIf="item.id == matchWithCondion ?func():false">
    Add your customized code here
  </div>
</div>

Initialize a variable in the typescript file like so:

let isFirstMatch = false;
 constructor(){}

 func() {
   if (!isFirstMatch) {
     this.isFirstMatch = true;
     return true;
   } else {
     return false;
   }
 }

In the HTML file again:

<div *ngFor="let item of list">
  <div *ngIf="item.id == matchWithCondion ? func() : false">
Add your custom code here
  </div>
</div>

Remember to initialize the 'isFirstMatch' variable in the typescript file:

let isFirstMatch = false; 

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

Required Field Validation - Ensuring a Field is Mandatory Based on Property Length Exceeding 0

When dealing with a form that includes lists of countries and provinces, there are specific rules to follow: The country field/select must be filled out (required). If a user selects a country that has provinces, an API call will fetch the list of provinc ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

Encountering a module not found error when attempting to mock components in Jest unit tests using TypeScript within a Node.js

I'm currently in the process of incorporating Jest unit testing into my TypeScript-written Node.js application. However, I've hit a snag when it comes to mocking certain elements. The specific error I'm encountering can be seen below: https ...

Managing clearing values/strings for different input types like text/password upon form submission in Angular2

Here is a code snippet for an HTML form: <div> <form class="form-horizontal" role="form" (ngSubmit)="createUser(Username.value, Password.value)"> <div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"> <input type="text" class=" ...

Efficiently managing repeated records in NodeJS using loops

I am trying to retrieve sales records for specific products from a table in my database based on client ID. This is how I attempted to achieve it: public async getData(clientID: any): Promise<any> { try { return await client .scan( ...

What causes the app to crash in release mode when importing a TypeScript component, while no issues arise in debugging?

Having an issue with importing a bottom sheet written in typescript into a class component. It works correctly in debugging mode but unfortunately not in release mode. Despite checking the logcat, no readable error code or message is being printed. Even a ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...

Adding an element within an ngFor iteration loop

I'm currently working on a code snippet that displays items in a list format: <ul> <li *ngFor="#item of items">{{item}}</li> </ul> These items are fetched from an API through an HTTP call. Here's the code snippet for tha ...

Retrieve an image from Azure Blob storage and directly deliver it to the client through a Node server without the need to store it

Is there a way to directly fetch an image from Azure blob storage and send it to the client without saving it locally? I have managed to retrieve the image from the blob storage and save it as a local file, but I am struggling to send it to the client with ...

The onClick event in HostListener is intermittent in its functionality

While attempting to create a dropdown box in Angular by following these examples, I am encountering inconsistent results. Below is the code I have used: HTML <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down">< ...

Angular 2 Release Candidate 6 form input pattern always fails to pass

How can I ensure that a required input in my form fails validation if there is no non-whitespace character present? Despite setting the pattern to [/S]+, the validation does not pass. Could I be missing an import or something else? My Template: <form ...

What is the best method for building and deploying an Angular-CLI 4 project across multiple environments?

We are in the process of deploying Angular to an Amazon S3 static website. Currently, we are creating separate builds for each environment (development and production). Is there a way to build once and deploy to all environments effortlessly? Thank you in ...

The Angular Date Pipe is currently unable to display solely the Month and Year; it instead presents the complete date, including day, month,

I'm currently using the Bootstrap input date feature to save a new Date from a dialog box. However, I only want to display the month and year when showing the date. Even though I added a pipe to show just the month and year, it still displays the mont ...

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

The angular schematic workflow encountered an error while attempting to create a new project

Successfully installed Angular CLI, but I encountered an issue while creating a new project using 'ng new project name'. Some packages were created, but the installation failed with an unexpected end in JSON while parsing near.....'A85qs.... ...

The directive is failing to apply the active class to the host element

My goal is to develop a directive that enables page scrolling when a menu item is clicked and also adds an 'active' class when the page is scrolled. Initially, I managed to implement page scroll on menu click successfully. However, I encountered ...

Creating your own custom operator using observables is a powerful way

const apiData = ajax('/api/data').pipe(map((res: any) => { if (!res.response) { console.log('Error occurred.'); throw new Error('Value expected!'); } return res.response; }), An enhancement is needed to encapsulate the ...

Looking for a shortcut in VSCode to quickly insert imports into existing import statements or easily add imports as needed on the go?

It seems that the current extensions available on the VSCode marketplace struggle to properly add Angular imports. For example, when I try to import OnInit using the Path IntelliSense extension: export class AppComponent implements OnInit It ends up impo ...

Accessing HTTP data through a function instead of using ngOnInit in Angular is a more efficient approach

Trying to retrieve data from a service using setInterval has posed an issue for me. When I call the service from ngOnInit, everything functions as expected. However, when attempting to call it from any other function, an error occurs: "ERROR TypeError: Ca ...

What is the method for substituting one text with another using two-way data binding?

I implemented two different cases in my Mat-Table. When there is no data, the user will see a message saying "No Data Found". However, if the user enters text in the filter search, the "No Data Found" message should be hidden and replaced with the entered ...