简体   繁体   中英

Search filter in Angular2

I am new to Angular 2. I am trying out the search filter function using the Pipe. However, I am unable to actually search for an item. I have been watching videos on how to search with filter, but they proved to be futile. Would appreciate if any of you can help me out here.

HTML File:

 <!--The content below is only a placeholder and can be replaced.--> <div style="text-align:center"> <h1> Welcome to {{title}}! </h1> </div> <form id="filter"> <label>Filter car by parts:</label> <input type="text" ng-Model="term"/> </form> <ul id="car-listing"> <li *ngFor ="let carPart of carParts | filter:term"> <h2> {{carPart.name | uppercase}} </h2> <p> {{carPart.description}} </p> <p *ngIf="carPart.inStock > 5"> {{carPart.inStock}} in Stock </p> <p *ngIf="carPart.inStock === 0"> Stock running low </p> <p> {{carPart.price | currency:'USD'}} </p> <p *ngIf="carPart.price === 350"> Special Promotion Only </p> </li> </ul> 

Typescript File:

 import { Component } from '@angular/core'; import {FilterPipe} from './filter.pipe'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'List of Car Parts'; carParts = [ { "id": 1, "name": "Regular Tires", "description": "Tires for city use", "inStock": 10, "price": 200, }, { "id": 2, "name": "Supreme Tires", "description": "Tires for all conditions", "inStock": 0, "price": 350, }, { "id": 3, "name": "Premium Tires", "description": "Tires for all luxury models", "inStock": 8, "price": 400, } ]; } 

filter.pipe.ts

 import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(carParts: any, term: any): any { if (term === undefined) return carParts; return carParts.filter(function(carPart){ return carPart.name.toLowerCase().includes(term.toLowerCase()); }) } } 

You are using ngModel incorrectly.

<input type="text" [(ngModel)]="term"/>

please check https://angular.io/api/forms/NgModel

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM