Angular Pipe: Working with Data Structures in Angular With Nested Arrays and Objects

After struggling to customize answers for similar questions, I find myself in need of some assistance.

My current challenge involves using an angular pipe to filter the following data structure:

subjects = [
      { name: "subject1", keywords:["keyword1", "keyword2", "keyword3"]},
      { name: "subject2", keywords:["keyword1", "keyword2", "keyword3"]},
    ];

I attempted to adapt an example with a simpler data structure:

subjects = [ "subject", "subject2"]

along with this custom pipe :

@Pipe({
  name: 'SearchPipe'
})
export class FilterPipe implements PipeTransform {

  transform(value: any, input: any): any {
   if (input) {
     return value.filter(val => val.toLowerCase().indexOf(input.toLowerCase()) >= 0);
   } else {
     return value;
   }
  }
}

However, I am struggling to adapt it to my specific use case.

The objective is to filter the data by keyword and display the matching names:

Edit: HTML Template:

    <div class="welcome-content" fxFlex="80">
        <div class="search-container">
            <mat-form-field class="textfield" appearance="standard">
                <mat-label>z.B. Flugverspätung</mat-label>
                <input class="input" matInput [(ngModel)]=subject>
            </mat-form-field>
        </div>
        <div class="subject-container">
            <div class="subject-list">
                 <div class="subjects" *ngFor="let subject of subjects | SearchPipe: subject">
                    <div class="subject-wrapper">
                        <a mat-button class="control-button" (click)="goToChat(subject)">{{subject.name}}</a>               
                    </div>
                </div>
            </div>
        </div>
    </div>

Any advice or tips would be greatly appreciated.

Answer â„–1

Upon reviewing your code implementation, I noticed that the value itself is the array provided in the ngFor. A more efficient approach to achieve your goal with the current data structure would be:

transform(values: any[]) {
    return values.filter(value => {
        // Check if it has a keywords filter array
        if (value && value.name && value.keywords) {
            // Return the value if there's any match
            return value.keywords.some(kw => {
                return value.name.toLowerCase().indexOf(kw.toLowerCase()) >= 0;
            }) && value;
        } else {
            return value;
        }
    });
}

UPDATE 1:

Here's a quick update based on the input field.

You used the same name as in the for loop, which won't work due to scope issues. You need to create a string property bound to the input field, such as textSubject.

<input class="input" matInput [(ngModel)]="textSubject">
...
<div class="subjects" *ngFor="let subject of subjects | SearchPipe: textSubject">
    <div class="subject-wrapper">
        <a mat-button class="control-button" (click)="goToChat(subject)">{{subject.name}}</a>               
    </div>
</div>

You must now pass a second argument to the transform function, which is the value of the input (textSubject in this case).

transform(values: any[], input: string) {
    return values.filter(value => {
        if (value && value.keywords && input) {
            // If matches, then return the value
            return value.keywords.some(kw => {
                return input.toLowerCase().indexOf(kw.toLowerCase()) >= 0;
            });
        } else {
            return value;
        }
    });
}

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

Sharing Pictures and Messages using angular, express, and multer

Struggling with posting images and text to the server while self-learning Angular. The backend works fine in Postman testing, but fails when working with Angular. Here is the code snippet I have been using: upload.component.html <form [formGroup]="upl ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

Is there a way to restrict the return type of a function property depending on the boolean value of another property?

I'm interested in creating a structure similar to IA<T> as shown below: interface IA<T> { f: () => T | number; x: boolean } However, I want f to return a number when x is true, and a T when x is false. Is this feasible? My attempt ...

Accessing file uploads in Angular 2

<div class="fileUpload btn btn-primary"> <span>Select File</span> <input id="uploadBtn" type="file" class="upload" value="No File Chosen" #uploadBtn/> </div> <input id="uploadFile" placeholder="No File Selected" disable ...

Guide to deploying angular universal starter kit on IIS - Configuring the Client Server setup

Currently, I am attempting to deploy an Angular Universal project onto IIS. I have set up a virtual directory pointing to the dist folder which contains both client and server folders. You can see the structure in this image: enter image description here ...

Angular routing is failing to redirect properly

After creating a sample Angular app, the goal is to be redirected to another page using the browser URL http://localhost:1800/demo. The index.html file looks like this: <!doctype html> <html lang="en"> <head> <title>Sample Ang ...

Using Angular alongside Firebase authentication and Material design causes the router to malfunction

Encountering issues with the router not functioning properly after firebase authentication. The problem appears to stem from @angular/animations, whether using NoopAnimationsModule or BrowserAnimationsModule, causing issues with the router functionality. ...

What causes the module declaration in the .d.ts file to fail in an Angular application?

I have recently created a file named global.d.ts within the src folder and it contains the following content: declare module 'ol-contextmenu'; Despite my efforts, placing the file in the root directory or in node-modules/@types did not solve the ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

Having trouble locating the export in the TypeScript module

Having a situation where there is a file with an exported object: let btypes:{[key:string]:any} = { "key1":val, //... } export {btypes} I even attempted to use export default btypes Upon importing it using: import {btypes} from "../types& ...

Incorporating real-time checked checkbox values into a running list

When displaying a list of preferences as checkboxes, I encountered an issue with the binding part. I am trying to capture the IDs of the checkboxes that are checked. Here is my attempt, which unfortunately does not work: <div class="checkbox" *ngFor="l ...

Having trouble with running the command ng update -g @angular/cli, receiving an error message

When running the command ng update -g @angular/cli I encountered the following issue: Unexpectedly, an error occurred stating package amcharts3-angular2 has no version null while trying to execute the ng update -g @angular/cli command. ...

Updating a property in a JavaScript object using Angular

Working with Angular, I have a dataset: export class AppComponent { data = [ { "area1": { "format": "changethis" } ] I am looking to develop a function that can alter the value of a specific key. For e ...

What strategy does Node recommend for organizing code into multiple files?

In the midst of my current project, which involves NodeJS and Typescript, I am developing an HTML5 client that communicates with a NodeJS server via web-sockets. With a background in C#, I prefer to organize my code into separate files for different functi ...

The parameter 'response' is assumed to be of type 'any' and is not explicitly declared

In my attempt to send data from an angular HTML page to MVC core and receive a response, I encountered an error when trying to use the subscribe method: Parameter 'res' implicitly has an 'any' type. Below is the code snippet: import ...

Attempting to run the command "npx typescript --init" resulted in an error message stating "npm ERR! could not determine executable to run."

What could be the reason behind the error message npm ERR! could not determine executable to run? Currently, I am attempting to set up a basic Node.js application using TypeScript and Yarn. Yarn is a tool that I am not very familiar with. These are the c ...

How to dynamically style a NgBootstrap modal in Angular during runtime

One of the features of my application is the ability to swap themes at runtime. The primary component in my app is called BaseComponent, which is added to my AppComponent and includes a theme property. This theme property represents a class that is applie ...

Encountering compilation errors during the vue-cli build process

My Vue 2.2.3 application is experiencing difficulties in the build process due to 4 TypeScript-related errors that are perplexing me. This is the error output displayed on the console: Failed to compile with 4 errors ...