Filtering data in Angular from an HTML source

Looking to filter a simple list I have.

For example:

<div *ngFor="let x of data"></div>

Example data:

  data = [
        {
         "img" : "assets/img/photos/05.jpg",
         "title" : "Denim Jeans",
         "overview": "today"    
        },
        {
         "img" : "assets/img/photos/05.jpg",
         "title" : "Denim jacket",
         "overview": "month"

        },
];

I only want to display items with the overview field set to month.

The expected implementation would be something like this:

*ngFor = "let x of data == overview"

Answer №1

Check out this solution:

<ng-container *ngFor="let x of data">
  <div *ngIf="x.overview === 'month'">
    <p>{{ x.title }}</p>
  </div>
</ng-container>

The ng-container acts as a way to apply logic like conditions or loops without creating an additional element in the HTML structure.

In this scenario, the container iterates through each item in the array while the inner div determines if it should be displayed based on the value of x.overview.

Answer №2

To efficiently filter data, you can create a custom pipe as shown in the example below:

<div *ngFor="let item of (data | customFilter)">
   {{item}}
</div>

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

@Pipe({ name: 'customFilter' })
export class CustomFilterPipe implements PipeTransform {
  transform(dataToFilter: any[]) {
    return dataToFilter.filter(item => item.filterProperty === 'value');
  }
}

For more information on pipes in Angular, visit https://angular.io/guide/pipes

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

Is it possible to utilize components or directives in both AngularJS and Angular when developing a hybrid application?

Is it possible to use AngularJS directives/services that have been "upgraded" in a hybrid app created with ngUpgrade for migrating from AngularJS to Angular? Can Angular components that are "downgraded" still be used on the Angular side as well? While res ...

The 'Content-Type' header cannot be defined for HTTP GET requests

I am currently working on setting up my GET requests to include the specific header: Content-Type: application/json Based on information from the documentation, I need to make the following adjustment: To customize these defaults, you can add or remov ...

Guide on creating a detailed list of categories mapped to specific classes that all adhere to a common generic standard

Most TypeScript factory patterns I've encountered rely on a named mapping between a name and the Class type. A basic implementation example: const myMap = { classOne: ExampleClass, classTwo: AnotherClass } (k: string) => { return new myMap[k] } ...

Issue with updating component

Currently facing an issue with a component that utilizes the changeDetection: ChangeDetectionStrategy.OnPush The component's logic is as follows: ngOnInit(){ this.serivce.something .subscribe( evt => { // Logic to update values of the ar ...

Customizing Angular Material select fields with border radius

I attempted to adjust the select field by adjusting the border radius, but it doesn't seem to be taking effect. I've made changes in the general style.css file, but so far, the issue remains unresolved. ...

Is there a way to retrieve the previously selected mat-tab in an Angular component, even after navigating to other components, without relying on localstorage or services?

Preserving mat-tab selection state between Angular components without relying on localStorage or a service Query: I'm currently developing an Angular application that features multiple components with mat-tab-groups. I would like to maintain the sele ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Path for WebStorm file watcher's output

I'm in the process of setting up a Typescript project in WebStorm, where I want the files to be transpiled into a dist folder. This is my current project folder structure: projectroot/src/subfolder/subfolder/index.ts What I aim for is to have the f ...

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

How can I restrict the highest possible date selection in reactjs?

I am working on a project that requires users to select dates using datetime-local, but I want to limit the selection to only three months ahead of the current date. Unfortunately, my current implementation is not working as expected. Any assistance woul ...

The issue with Angular Material Dialog hiding certain elements

In my Node.js Angular project, I am trying to implement a confirm dialog which should be a simple task. Utilizing Material styling to speed up development process. However, upon running the project, the opened dialog appears to be empty: https://i.sstati ...

Mysterious attributes of angular 6's <table mat-table> tag

This particular question regarding the angular material table has not been duplicated in any other discussions. Other similar questions pertain to angular versions 2-5, not version 6 The issue I am encountering is as follows: Can't bind to 'dat ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Error Encountered: White screen issue affecting Ionic 6 / Angular 14 app running on Android 6.1 device without Google Mobile

After successfully deploying my new Ionic 6 / Android 14 app on multiple devices, I encountered a problem with one specific device - a Zebra ET50 running Android 6.1 without Google Mobile Services. The app fails to load and only shows a white screen. I no ...

Is it possible to configure TypeScript (or a tool similar to ESLint) to throw an error when a library returns undefined?

Currently working with knex and sometimes it returns any, for example when forgetting to specify the table type in the query. Are there any recommended tools available to avoid this issue, ensuring all knex queries are typed properly? ...

Customizing the colors of the Input field in the Material UI Text Field component with CSS styling can elevate the overall

import { TextField } from "@mui/material"; import { FunctionComponent } from "react"; interface IProps { type: string; label: string; color: | "error" | "primary" | "secondary" | &quo ...

Is there support for TypeScript in express-openid-connect?

Is there any documentation available for using express-openid-connect with TypeScript, or if it is supported at all? ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...