Explore the capabilities of the Angular Ng2SearchPipeModule to enhance your search input

I used the ng2SearchPipeModule for an input search, but it's not working. I can't seem to find my error. In my HTML, all my books are within divs. Will typing a book title display all the divs?

Of course, I have imported in app.module.ts Ng2SearchPipeModule and FormsModule.

I am facing two errors:

1 - Property 'filter' does not exist on type 'BookType'.

2 - Nothing is happening in my HTML.

service.ts

export class BookService {

  url: string = 'http://henri-potier.xebia.fr/books';

  constructor(private http: HttpClient) { }

  getBookList(): Observable<BookType> {
    return this.http.get<BookType>(this.url);
  }
}

component.ts

import { Component, OnInit } from '@angular/core';
import { BookType } from '../models/book-type';
import { BookService } from '../services/book.service';

@Component({
  selector: 'app-content',
  templateUrl: './content.component.html',
  styleUrls: ['./content.component.css']
})
export class ContentComponent implements OnInit {

  public bookType: BookType;

  constructor(private bookService: BookService) { }

  ngOnInit(): void {
    this.bookService.getBookList().subscribe(data => {
      this.bookType = data
    });
  }

  search() {
    if(this.bookType.title == "") {
      this.ngOnInit();
    }else{
      this.bookType = this.bookType.filter(res =>{
        return res.bookType.title.toLocaleLowerCase().match(this.bookType.title.toLocaleLowerCase());
      })
    }
  }

}

html

 <input class="form-control" type="text" name="search" [(ngModel)]="bookType" (ngModelChange)="search()"
    placeholder="Rechercher">
    <div class="grid-container">
        <div class="wrapper" *ngFor="let book of bookType" class="form-group">
            <div class="product-img">
                <img [src]="book.cover" alt="livre" height="420" width="327">
            </div>
            <div class="product-info">
                <div class="product-text">
                    <h2>{{book.title}}</h2>
                    <p>{{book.synopsis}}</p>
                </div>
                <div class="product-price-btn">
                    <p>{{book.price | currency: 'EUR'}}</p>
                    <button type="button" (click)="addBookToCart()">buy now</button>
                </div>
            </div>
        </div>
    </div>

interface

export interface BookType {
    title: string;
    price: number;
    cover: string;
    synopsis: string;
}

Answer №1

It seems that the reason you are dealing with an array for bookType is because you are iterating through it using *ngFor. To address this, make sure to declare bookType as an array like so:

public bookType: BookType[];

By doing this, you are indicating that the property holds instances of BookType within an array structure. Once you have made this adjustment, you will be able to utilize this.bookType.filter() since filter() functions work specifically with arrays.

This should resolve the issue at hand.

Note: Regarding your comment query

You can create another property of type BookType in the following manner:

public searchedBook: BookType;

Take note that this time there is no array designation with [] Now incorporate this property into the ngModel using the syntax below:

[(ngModel)]="searchedBook"

Subsequently, proceed as follows:

this.bookType = this.bookType.filter(res =>{
        return res.title.toLocaleLowerCase().match(this.searchedBook.title.toLocaleLowerCase());
})

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

Guide on retrieving the interface property name or key name as a string in Typescript

Currently, I am utilizing the API of Slack and encountering situations where I send JSON requests containing strings that return as property names later on. I want to create an interface where I can send one of its property names as a string and receive t ...

Utilize the prototype feature from a versatile source

Can a class with a generic like class Foo<A> {} access A's prototype or use a typeguard on A, or perform any kind of logic based solely on A's type - without being given the class, interface, or instance to Foo's constructor (e.g. when ...

How can you compare input text to the input value attribute using jQuery?

Consider this scenario: the page displays the following input element... <input class="textInput error" id="accountMailaddress" name="user[email]" size="30" type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

An issue is preventing the Angular 2+ http service from making the requested call to the server

I am looking to create a model class that can access services in Angular. Let's say I have the following endpoints: /book/:id /book/:id/author I want to use a service called BooksService to retrieve a list of Book instances. These instances should ...

What is the best way to interpret a line break within a string variable in TypeScript?

Realtime Data base contains data with \n to indicate a new paragraph. However, when this data is retrieved and stored in a String variable, the website fails to interpret the \n as a paragraph break: https://i.stack.imgur.com/tKcjf.png This is ...

What is the best method to retrieve HTTP headers from the backend and simultaneously send HTTP parameters to it in ASP.NET Core and Angular?

I am currently working with Angular 15 and ASP.NET Core 5. The backend retrieves paged items based on the parameters pageSize and pageIndex. Once the action method receives the pageSize and pageIndex parameters, it sends both the paged items and the total ...

The HostListener feature ceased to function properly following an upgrade to the newest version of Angular (Version 15)

After upgrading to angular 15, I encountered an issue with the following code. The line `this.ngControl.value` is returning blank instead of the expected value. Has anyone else experienced this and found a solution? import { Directive, HostListener } fro ...

The ApexCharts Radar Chart always pushes the data to its maximum potential, creating visually stunning charts that showcase

It appears that with apex charts, the radar chart always scales to the data you have specified. Is it possible for the radar chart to scale to the maximum value instead of just the maximum data value in the series? Based on kikon's response and his ...

Ensuring the Current Page is Valid Before Progressing to the Next Step in Angular-Archwizard

Currently, I am working with Angular-7 and using angular-archwizard to create a multi-step form. The issue I am facing is that the form allows users to proceed to the next step without filling in all the required fields. My goal is to restrict users from m ...

I am faced with a challenge involving an asynchronous function and the best approach to executing it synchronously

I devised the following plan: // Primary Function to Follow // Capture necessary local data // Transform into required editable format // Iterate through user's local images // Append image names to converted d ...

Unable to Sort Angular Material Data Table

Struggling to organize my data as the sorting functionality is not behaving as expected. Unlike the typical examples that use a local array of values, my situation involves an API call that returns an array of objects, with each object containing a 'n ...

Incorporating a particular JavaScript library into Angular 4 (in case the library doesn't have a variable export)

I am attempting to display the difference between two JSON objects in an Angular 4 view. I have been using a library called angular-object-diff, which was originally created for AngularJS. You can view a demo of this library here: Link I have trie ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here. Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer ...

"Take control of FileUpload in PrimeNG by manually invoking it

Is there a way to customize the file upload process using a separate button instead of the component's default Upload button? If so, how can I achieve this in my code? Here is an example of what I've attempted: <button pButton type="button" ...

Learn the process of automatically copying SMS message codes to input fields in Angular17

After receiving the first answer, I made some changes to the code. However, when testing it with Angular, I encountered several errors. How can I resolve these issues? TS: async otpRequest() { if ('OTPCredential' in window) { const ab ...

Utilizing Business Logic in a MEAN Stack Environment

When developing an Angular application, where should the calculations take place - on the front end or back end? Considering that the outputs need to update with each input change, is it practical to send a request to the back end every time there is an ...

Sign up for notifications about updates to a variable within an Angular service

Is there a way to track changes in the value of a variable within an Angular service? I've been searching for a solution, but haven't been able to find one yet. In my layout's header component, I have a counter that displays the number of ...