简体   繁体   English

Angular2中的搜索过滤器

[英]Search filter in Angular2

I am new to Angular 2. I am trying out the search filter function using the Pipe. 我是Angular 2的新手。我正在尝试使用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: HTML档案:

 <!--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 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. 您使用的ngModel不正确。

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

please check https://angular.io/api/forms/NgModel 请检查https://angular.io/api/forms/NgModel

Hope it helps!! 希望能帮助到你!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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