How can I utilize Angular 5's forEach method to view search results?

Can we implement a search and filter functionality using forEach method? I have 4 dropdown lists and a submit button. For example, when one or two criteria are selected and the submit button is clicked, the results will be displayed in a dataTable.

For instance, selecting the value "ABC" will show all data containing the word "ABC". Is this possible?

Below is the HTML code used for filtering and searching:

<div class="nd_panel form_filter_home fixed" id="panel-filter-search-container">
  <h6 class="accordion-toggle" href="#filters" (click)="toggleCollapse($event)">
    <span class="glyphicon glyphicon-filter text-primary"></span>
    <label>{{ 'search-filtre' | translate }}</label>
  </h6>
  ...
  ...
  ...
  
  </form>
</div>

The onSubmit function is used to handle the form submission and display filter results based on the selected criteria.

onSubmit(searchFormValue): void {
  if (this.isValid(searchFormValue)) {
    if (searchFormValue === searchFormValue.SelectedEntity) {
      // do something to display filter results 
    }
  }
}

In the following script, values displayed on the dropdown lists are initialized during component initialization:

ngOnInit(): void {
  this._userService.getEntities().subscribe(
    entities => {
      this.entities = entities;
      entities.forEach(entity => {
        if (this.entityTypes.filter(tp => tp.value === entity.type).length === 0) {
          this.entityTypes.push({ value: entity.type, label: entity.type });
          this.displayedEntityTypes.push({ value: entity.type, label: entity.type });
        }
        if (this.entityProfiles.filter(tp => tp.value === entity.profil).length === 0) {
          this.entityProfiles.push({ value: entity.profil, label: entity.profil });
          this.displayedEntityProfiles.push({ value: entity.profil, label: entity.profil });
        }

        this.entityCodes.push({ value: entity.code, label: entity.code });
        this.displayedEntityCodes.push({ value: entity.code, label: entity.code });
      });
    },
    err => {
      console.log(err);
    }
  );
}

Answer №1

It's important to store the filter value that is submitted into a public variable within your component:

onSubmit(searchFormValue): void {
    if (this.isValid(searchFormValue)) {
      if (searchFormValue === searchFormValue.SelectedEntity) {
        this.submittedFilter = searchFormValue;
      } 
    }
}

Afterward, you can utilize an *ngFor directive to display the entities:

<div *ngFor="let myEntity of entities | myCustomFilter: submittedFilter"><div>

To create a 'myCustomFilter', use the @Pipe annotation as shown below:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'myCustomFilter'})
export class MyCustomFilter implements PipeTransform {
  transform(entity: string, filter: string): number {
    // Define the desired behavior here
    // 'entity' can be a custom object
    return entity.includes(filter);
  }
}

EDIT:

If manual data filtering in code is preferred over HTML-based filtering, you can import your custom pipe and implement it within a method:

import { MyCustomFilter } from 'path/to/your/pipe';
constructor(private myCustomPipe: MyCustomFilter ) {}

// Apply the custom pipe to filter entities
filterEntities() {
  return myCustomPipe.transform(this.entities, this.submittedFilter);
}

Bind the method to the input value like so:

<p-table [value]="filterEntities()">
<p-table>

I hope this explanation proves helpful :)

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

Discover the steps to create a virtual scroll dropdown menu with Kendo in Angular

I'm dealing with a large data set obtained from an API. Instead of displaying all the data in the dropdown initially, I'd like to fetch the results from the server API as the user scrolls down through the dropdown menu. Could someone please prov ...

There is a type error in the dynamic assignment in TypeScript. I have various data that need to be fetched from one another

const obj1 = { a: 1, b: "xx" }; const obj2 = { a: 2, b: "3", d: "hello" }; for (const key in obj1) { const _key = key as keyof typeof obj1; obj1[_key] = obj2[_key]; } x[_key] error Type 'string | number' is no ...

Issue with Angular routing: encountering a 404 error indicating page not found

I'm facing an issue with routing in my Angular application. All components were working fine previously, but suddenly none of the components are accessible today. Whenever I try to access a specific path, I receive an "error 404 /test" message from An ...

Populating a Modal Popup with an Angular 2 Module

I am currently implementing angular 2 with bootstrap. On my dashboard page, I have a specific requirement where when a user clicks on any link, a new module should appear in a modal popup. Can you provide guidance on how to accomplish this task? Since my ...

Zendesk API integration with Angular is experiencing issues with retrieving data as a result of a CORS restriction

I have been working with the Zendesk API and have encountered a problem. Despite being able to successfully send POST requests (even though the response indicates an error), I am unable to make GET requests using my Angular 4 application along with HttpCli ...

Efficient ways to exchange data at the application level across pages in Angular 2 and higher versions

Throughout my experience with various Angular projects, I have encountered the challenge of effectively sharing application-level data between different pages. There are several methods to tackle this issue, such as using a service and injecting it into p ...

When working with data in Angular, make sure to use any[] instead of any in app.component.html and app.component.ts to avoid causing overload errors

I'm new to working with Angular, specifically using Angular 15. I have a Rest API response that I need to parse and display in the UI using Angular. To achieve this, I employed the use of HttpClient for making GET requests and parsing the responses. ...

Guidance on implementing a Cypress assertion for a JavaScript object retrieved via ag-Grid

Seeking guidance as I navigate the world of UI automation and Cypress, specifically in setting up assertions on JavaScript objects returned by the cypress-ag-grid package Currently, my code is extracting data from ag-grid cy.get("#myGrid").getAg ...

Exploring the process of defining a generic type for a function which accepts any Static Model and outputs instances of that Model using Sequelize

My task involves defining a function named FieldSearch with specific parameters: fieldSearch<SpecificModel extends Model>( model: ModelStatic<SpecificModel>, // Struggling with this part fields: Array< attributes of the static model p ...

Steps for gracefully throwing an error to an Angular RxJS Observable consumer

How can I handle errors from the 'BROKEN' line in this function so that they are passed to its subscriber, similar to how the 'WORKS' line does? I have observed that the 'Works' line successfully sends the error to this funct ...

Ways to dynamically update the state of a mat-button-toggle-group programmatically

I'm currently working on implementing a confirmation dialog to change the state of MatButtonToggleGroup. However, I am facing an issue where I need to prevent the default behavior unless I revert to the previous state upon cancellation. Here's t ...

Regulation specifying a cap of 100.00 on decimal numbers entered into a text input field (Regex)

I have created a directive that restricts text input to only decimal numbers in the text field. Below is the code for the directive: import { HostListener, Directive, ElementRef } from '@angular/core'; @Directive({ exportAs: 'decimal ...

Organize the attributes of components on the following line in Visual Studio Code

Is there a method to configure the VS code formatter for Angular 2+ templates to ensure that attributes are wrapped in a new line? I prefer this formatting: <app [input1]="input1$ | async" [input2]="input2$ | async" (inputChanged)="set ...

When converting an NgbDate to a moment for formatting needs, there is a problem with the first month being assigned as 0 instead of 1

I am encountering a challenge with my Ngb-Datepicker that allows for a range selection. To customize the output format, I am using moment.js to convert the NgbDate into a moment object (e.g., Wed Jan 23). One issue I encountered was that NgbDates assign J ...

The error occurred due to passing along an 'undefined' value instead of a stream which was expected. Make sure to provide an Observable, Promise, Array, or Iterable. This issue was raised within the context of <Jasmine

Hey, I've implemented this code snippet in ngOnInit for polling, but it's causing all my test cases to fail. Can someone please assist me in resolving this issue? ngOnInit(): void { this.timeInterval = interval(5000) .pipe( startWith(0), sw ...

Issue with Angular: Global variable not updating within Subscription function

I'm encountering difficulties with updating a global variable in Angular 7 by using TypeScript. I am utilizing a service that retrieves JSON data from a database via a Restful API The service : export class myService { constructor(private client ...

Transform event binding using PrimeNG Elements and Angular

My challenge lies in dynamically binding change events within the PrimeNG TreeTable by defining functions on my columns. I've noticed that attempting to bind the change event dynamically with my columns doesn't seem to work properly inside the Tr ...

Encountering an ENOENT error in the CodeSandbox CI environment, whereas this issue does not arise in GitHub

I am currently in the process of creating a GitHub pull request for the react-querybuilder library. However, I am encountering an issue with my CodeSandbox CI job, which is failing and displaying the following error message: { [Error: ENOENT: no such file ...

Error parsing Angular2 with ngFor directive

I'm attempting to utilize the ngFor directive in an angular 2 (alpha 35) project, but I keep encountering the error EXCEPTION: Can't bind to 'ngforOf' since it isn't a known property of the '' element and there are no mat ...

Retrieve a specific key from a TypeScript interface

It seems like there might be a problem with this code snippet: interface import {BrowserService} from "../services/browser/index"; export interface IPrimaryNavigation { opts:IPrimaryNavigationOpts; } export interface IPrimaryNavigationOpts { .. ...