The filter pipe in Angular 7 is not functioning properly

Upon page loading and API call initiation, I am encountering an issue with the ngFor loop not displaying all the values. However, when I manually input a search query in the search box for filtering, the functionality works flawlessly. My goal is for all values to be shown without the search filter being applied initially during page load.

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

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(value: string, filterString: string, propName: string): any {
    if (value === null && value.length < 1 || filterString === '') {
      return value;
      /*This value doesn't show when the filter isn't applied on load*/
    }
    const resultArray = [];
    for (const item of value) {
      filterString = filterString.toLowerCase();
      if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
          resultArray.push(item);

    }
  }
    return resultArray;
 }
}
/*Component*/
  ngOnInit() {
    this.api.getStopData().subscribe(
      data => {
        this.stations = data;
      }
    );
  }
<div class="container">
<form class="form-inline md-form form-sm active-pink-2 mt-2">
  <input class="form-control form-control-sm mr-3 w-75" name="search" [(ngModel)]="search" type="text"
    placeholder="Search train stations" aria-label="Search">
  <i class="fas fa-search" aria-hidden="true"></i>
</form>
<!-- Card -->
<div *ngFor="let station of stations?.results?.objStation | filter:search:'StationDesc'">
<mdb-card class="m-1">
  <!--Card content-->
  <mdb-card-body>
    <!--Title-->
    <mdb-card-title>
      <h4>{{station.StationDesc}} Train Station</h4>
      <hr/>
    </mdb-card-title>

    <img class="col-6 panel-realtime" src="assets/img/icon_view.png" (click)="getStation(station.StationCode); basicModal.show()"
      mdbWavesEffect>
    <img class="col-6 panel-remove" src="assets/img/thumbnail_icon_map.png" (click)="getMaps(station.StationDesc); mapsModal.show()" mdbWavesEffect>

  </mdb-card-body>
</mdb-card>
</div>
</div>

Answer №1

It seems like the search variable is not being initialized in your code. If you do not initialize the search variable in your component.ts file, then on page load, the value of search will be undefined instead of ''.

Here is a possible solution:

export class Component implements OnInit{
  search: string;

  constructor() {
   this.search = '';
  }

  ngOnInit() {
    this.api.getStopData().subscribe(
      data => {
        this.stations = data;
      }
    );
  }
}

Another solution option:

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

@Pipe({
  name: 'filter',
})
export class FilterPipe implements PipeTransform {
  transform(value: string, filterString: string, propName: string): any {
    if (value === null && value.length < 1 || (filterString === '' || filterString === undefined)) {
      return value;
      /*This value isn't returning when filter isn't applied on load*/
    }
    const resultArray = [];
    for (const item of value) {
      filterString = filterString.toLowerCase();
      if (item[propName].toLowerCase().indexOf(filterString) >= 0) {
          resultArray.push(item);

    }
  }
    return resultArray;
 }
}

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

ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When ...

Issue arising from passing an object through a component in a Next.js application during build time when the object is retrieved from a database

Can anyone provide assistance with solving this issue? I have an object called "diary" coming from a database, which is passed to a component where a useState hook is expecting that object. During build time, the following error is occurring. An error is ...

Replicating the Angular project folder is not effective

Instructions for using Angular's quickstart script are as follows: git clone https://github.com/angular/quickstart.git quickstart cd quickstart npm install npm start If I follow these steps, everything works perfectly. However, if I duplicate this d ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

Looking for a way to display a spinner loader while transitioning between routes in Angular 4? Although I'm receiving events, I'm struggling to actually show the loader on screen

I'm currently working on a project that requires a loader to display between two routes. Although I am receiving route events, the loader is not visible. import { Component } from '@angular/core'; import { Router, Event, NavigationStart, Na ...

Trouble with Angular 2 HTTP post: body not being transmitted correctly

I'm currently facing issues with the following code: var express = require('express'); var router = express.Router(); var mongojs = require('mongojs'); var db = mongojs('mongodb://lee:<a href="/cdn-cgi/l/email-protectio ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Tips for transferring request variables/data from a middleware to another function in typescript

I need to authenticate a user's jwt token using middleware. This is the middleware I have: const authorized = (req: Request, res: Response, next: NextFunction) => { const token = req.header("token") if(!token){ return res.send("N ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...

Continuous Updates to innerHtml in Angular2

While working on a project, I encountered an issue that seems to be more about style than anything else. The endpoint I am calling is returning an SVG image instead of the expected jpeg or png format, and I need to display it on the page. To address this, ...

Angular is expecting data of type string or number for the operands provided

When working in VS Code, I encountered the following warning: "Expected operands to be a string or number type" https://i.stack.imgur.com/lULLQ.png The contentType variable is defined as a string. I noticed that when I remove 'data:', every ...

The type (string | undefined) cannot be assigned to type string[] even when using the .filter function to remove undefined elements

Consider the following code: let someVar: Array<string>; somevar = ["a", "b", undefined, "c"].filter((it) => !!it); The code above is resulting in an error: Type '(string | undefined)[]' is not assignable t ...

Typescript: Utilizing Index-Based Callback Parameters in Functions

I am currently working on creating a function that can handle specific data types ("resource") along with an array of arrays containing call objects and corresponding callbacks for when the calls finish ("handlers"). function useHandleResource< R exte ...

Retrieving an array of objects through an Angular service

I'm fairly new to Angular and Javascript. Recently, I created an Angular service that fetches an array of users from an HTTP call returning JSON data. While the HTTP call is successful and returns the correct data, I'm having trouble passing this ...

What is the rationale behind an Angular component needing to duplicate an object provided by a service?

As I dive into the HttpClient page within the Angular Fundamentals section, one question that comes to mind is why does the component need to clone the object received from the service handling the HTTP calls? In particular, the code block from the config ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Choose a value, then multiply it by a number using a reactive

I have been attempting to multiply a fixed value by the selected value of a mat-select element, for example A x B, where A remains constant and does not change while B is the changing value from the mat-select. After performing this multiplication, I aim ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

TypeScript: displaying parameters

variable_field = [["S",".","."],[".","#","."],[".",".","T"]]; <ng-template ngFor let-array [ngForOf]="field_array" let-x="index"> <ng-t ...