我是Angular 2的新手。我正在使用Pipe尝试搜索过滤器功能。但是,我无法实际搜索项目。我一直在观看有关如何使用滤镜进行搜索的视频,但事实证明这些视频是徒劳的。如果你们中的任何人可以帮助我,我将不胜感激。
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>
打字稿文件:
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());
})
}
}
答案 0 :(得分:0)
您正在错误地使用ngModel。
<input type="text" [(ngModel)]="term"/>
请检查https://angular.io/api/forms/NgModel
希望它有所帮助!!