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

What is the best way to set a Firestore data field as a variable?

I am working with a firebase collection named 'messages', where I add documents as follows: this.afs.collection('messages').add({ 'qn': message, 'student': this.student, 'upvotes': this.upvote }); The upv ...

What are the requirements for loading styleUrls in an Angular component?

How can I implement multiple CSS files in the styleUrls array? @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [conditional statement for loading specific CSS] }) I have attempted it before, bu ...

Having trouble retrieving the Angular CLI version even after ensuring all the necessary requirements are installed?

I am facing challenges with using the Angular CLI. I have successfully installed Node, NPM, and Angular, as confirmed by running the which command in the terminal showing their locations in /user/local/bin. The current version of my node.js is v11.8.0. T ...

Retrieve the API output and save the information into an array

I am struggling with calling an API in my Angular application and extracting specific data from the JSON response to populate an array. Although I am able to retrieve the response, I am having trouble isolating a particular field and storing it in an array ...

A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON fi ...

Steps for generating an instance of a concrete class using a static method within an abstract class

Trying to instantiate a concrete class from a static method of an abstract class is resulting in the following error: Uncaught TypeError: Object prototype may only be an Object or null: undefined This error occurs on this line in ConcreteClass.js: re ...

Is it possible to conceal dom elements within an ng-template?

Utilizing ng-bootstrap, I am creating a Popover with HTML and bindings. However, the ng-template keeps getting recreated every time I click the button, causing a delay in the initialization of my component. Is there a way to hide the ng-template instead? ...

FirebaseError: Trigger parsing error: Module 'grpc' not found

I'm currently working on setting up an Angular4 application with Server Side Rendering (SSR) using Angular Universal and Firebase Cloud Functions. While the application works smoothly with ng serve, I encountered an issue after building the app and s ...

Is it necessary to include a module in another module if it is not utilized in the template?

Is it necessary to import Module2 into Module1 if a component from Module2 is being used in Module1, but only in the typescript and not the template? For instance, as a @ContentChild(Component2) component2 like shown below (Note: both modules are secondary ...

Utilizing the Angular formArrayName directive in form elements

The Angular official documentation provides the following code example: @Component({ template: ` <form [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> ...

Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section: The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

How can I exclude *.d.ts files from tslint checking?

Recently, I decided to integrate tslint into my workflow. Following the installation steps, I used the command: npm install tslint tslint-config-ms-recommended --save-dev My configuration file tslint.json now looks like this: { "extends": "tslint-co ...

Node.js Request GET is serving unprocessed data rather than JSON format

Seeking assistance with a unique challenge - I am attempting to utilize the Stackoverflow Search/Advanced API to query stackoverflow for questions. While testing in PostMan, I successfully received JSON data, but when implementing the request in my Node.js ...

What is the best way to target all select2 elements with a single button click?

Utilizing the Select2 feature of angular for multiple selection, I am in need of a function that allows me to select all elements with a single click on a button or checkbox. https://www.npmjs.com/package/ng-select2 My attempt at inserting all ele ...

The function to increase the number of days on a date in Angular is experiencing technical issues

I'm facing an issue where I need to add 12 days to a specific date, but the new date is not coming out as expected. Below is the code snippet: addDays(days: number): any { let startDate = new Date(this.selectedDeliveryDate); let endDate = new ...

Error relating to Power bi date filter

Having trouble with the Power BI date slicer displaying calendar month/days in a language other than English, appearing like Spanish. After publishing to app.powerbi.com (dashboard), the report displays correctly in English. Similarly, on Local Power BI ...

Unable to retrieve this information within an anonymous function

I am currently working on converting the JSON data received from an API interface into separate arrays containing specific objects. The object type is specified as a variable in the interface. Here is the interface structure: export interface Interface{ ...

Having trouble installing angular/cli on Windows7 64 bit using npm?

I am currently facing an issue while attempting to install angular-cli using the latest versions of npm (5.3.0) and node (v8.2.1) on a Windows7 64-bit environment. Both npm and node are functioning properly as expected. However, the installation process f ...

One of the interfaces in use is malfunctioning, despite being identical to the other interface in TypeScript

I have been working on the IDocumentFilingDto.ts file. import { DocumentOrigin } from "./IDocumentFilingDto"; export interface IDocumentFilingDtoGen { UniqueId?: any; Title?: string; DocumentId?: string; Binder?: any; Communi ...