Achieving filtered data post *ngFor in Angular2 component

Trying to retrieve a filtered list of data in my component. In the view, I have something similar to this:

<ng-container *ngIf="(items | filter:search.value) as result">
  <div *ngFor="let item of result">
    {{item}}
  </div>
</ng-container>

Now, I need to access the result from the component. One way is to add {{result_setter(result)}} to the ng-container and create a method with a variable in the component:

filtered_data;

result_setter(data) {
  this.filtered_data = data;
}

However, this approach doesn't look very clean. Can someone provide assistance? I came across this article , where users in the comments are facing a similar issue.

Answer №1

Pipes in Angular are designed to display data exclusively.

If you wish to filter and retrieve values in your component, it is recommended to apply the filtering process upon query change.

<input type="file" [(ngModel)]="search" (input)="filterData">

filterData() {
  this.filteredData = this.data.filter(item => /* implement your desired filtering logic here */);
}

UPDATE Another approach is to utilize an instance of the pipe for data filtering like demonstrated below:

filterData() {
  const pipe = new FilterPipe(); // It might be advantageous to declare this as a class property
  this.filteredData = pipe.transform(this.data, this.search);
}

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

Executing End-to-End Tests using Protractor in Conjunction with Angular version 4

I recently encountered some issues while trying to run end-to-end tests for an Angular 4 project that I'm working on! Despite my efforts, I couldn't figure out how to resolve the errors I've been facing. Below is the error message I receiv ...

Decoding the logic behind the *ngIf directive

Context In my code template, I am iterating over data retrieved from an HTTP response. <div *ngFor="let method of paymentMethods"> Within this loop, I am displaying method?.payment_profile_id Now, I want to display one of two elements based on ...

Tips for preventing the rxjs error "TypeError: Cannot read properties of undefined" in the Angular framework

When I try to open the page in Angular, I encounter this error: core.mjs:6485 ERROR TypeError: Cannot read properties of undefined (reading 'getDocumentContent') In my Angular component, I have an observable like this: selectedDocument$ = this.s ...

Is it compatible to use Typescript version 2.4.2 with Ionic version 3.8.0?

Is it compatible to use Typescript 2.4.2 with Ionic 3.8.0? $ ionic info cli packages: (C:***\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.18.0 ionic (Ionic CLI) : 3.18.0 global packages: cordova (Cordova CLI) : not insta ...

What is the proper way to access the global `angular` variable in Angular and TypeScript when using AngularJS?

I'm currently integrating an Angular 4 component into a large monolithic AngularJS application. The challenge I face lies in the restrictions of the AngularJS project's build system, which limits me to only modifying the project's index.html ...

Error in Capacitor Native App with Azure AD due to Cross-Origin Token Redeem Failure

I am currently working on a native application using Angular, Angular OIDC Client, and Capacitor. However, I am facing an issue with authentication when trying to connect with Microsoft Azure AD. The error message present in my Xcode logs reads as follows: ...

Issue: Unable to locate a change supporting element '[object Object]' of the type 'object - Angular 7'

An angular service has been created for the specified purpose: CheckTicket(barcode, codEspec, diaHoraEspec):Observable<Ticket[]>{ //read ticket return this.http.get<Ticket[]>(`${this.checkticket_url}${barcode}?token=${this.token}&a ...

When you refresh the page, the number of items in the cart displayed on the navbar always shows 0

When using my angular application, I encountered a problem with adding movies to a cart. Although I can successfully add them to the cart and see the correct number of movies reflected in the navbar, upon refreshing the page, the count resets to 0. Here i ...

Mastering the Art of HTML Binding in Angular 8

I am facing a challenge in Angular 8 with displaying HTML content. The app I'm building in Angular 8 has a Flask backend that sends JSON data containing an HTML template to the frontend. My goal is to render this template in Angular. Here is the JSON ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

Testing an asynchronous function in JavaScript can lead to the error message: "Have you neglected to utilize await?"

Here is an example of the code I am working with: public getUrl(url) { //returns URL ... } public getResponseFromURL(): container { let myStatus = 4; const abc = http.get(url, (respon) => const { statusCode } = respon; myStatus = statusCode ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Angular array of considerable size

Dealing with a massive array of 30,000 items can be quite daunting, especially when it comes in as a stream using grpc-web. Currently, I'm fetching the data from grpc.client() and populating an array before displaying it using *ngFor. However, I' ...

Sending Angular POST requests with Date fields in a specific format for serialization

New to Angular and unsure of the best approach to serializing a Date property when adding an object to a POST request. Taking into account the sample class below: export class MyClass{ public dateProperty: Date; } The service code snippet is as follo ...

A guide on integrating ngrx-store with a canLoad guard for optimal functionality

Is this a recommended practice? Below is what I am attempting to do: I have two lazy loaded modules: ManagementModule and ConfigurationModule, with the following route configuration: const routes: Routes = [ {path: '', redirectTo: 'manag ...

How might one utilize the latest Angular control flow syntax to conditionally enclose a <span> with an <a> tag

I am seeking a solution to conditionally wrap a span with an anchor tag to create a link. There are multiple approaches to accomplish this, but I am curious if there is an optimal method. Here is the desired outcome: If the item has a URL, the HTML should ...

Modify the class of the focused element exclusively in Angular 2

I'm working on a project that involves several buttons and div elements. Currently, the divs are hidden, but I want to be able to reveal a specific div when its corresponding button is clicked. For example: If you click the first button, only the fir ...

Where can I find the refresh token for Azure Single Sign-On with MSAL?

Currently, I am working on integrating SSO for my application using Angular and .NET 2.2. I have come across a roadblock with the refresh token. While the login process is functioning correctly and the service is sending a lot of login information, the ref ...

Utilizing Input Values in Angular Components - A Step-by-Step Guide

I am a beginner in Angular and attempting to build a basic todo application. I have utilized [(ngModel)] to send the input value to the component, but it seems that I am doing it incorrectly. Below is my code: HTML: <div class="todo-app"> <h ...

RouterLink functionality stops working after the first click

Currently working on an Angular 4 project with a parent component A that contains a [routerlinkA] in the HTML, linking to component B. Component B then has another [routerlinkB] to return to A. Initially, everything functions perfectly. However, after mak ...