开发思路:
- 应用响应式编程获取搜索关键字的值
- 应用管道来根据股票关键字来过滤股票信息
思路1实现:
第一步:在app.module.ts中加入两个模块,FormsModule,ReactiveFormsModule
imports: [
BrowserModule,
RouterModule.forRoot(routerConfig),
FormsModule,
ReactiveFormsModule,
],
第二步:在stock-manage.component.ts中创建一个FormControl类型的对象,用以时时检测表单的变化
import {FormControl} from '@angular/forms';
public searchInput:FormControl=new FormControl(); //创建一个FormControl对象,用于发射valuechange事件来检测被绑定的input的value的变化
第三步:想要实现第二步中描述的用FormControl类型的对象时时检测表单的变化,就需要将表单和创建的FormControl类型的对象绑定到一起,绑定的语法指令就是[formControl]="创建的FromControl对象",在stock-manage.component.html中实现:
<input [formControl]="searchInput" type="text" placeholder="股票名称">
第四步:此时就可以时时的检测表单的变化,用创建的FormControl对象发射valueChanges事件,并且订阅这个事件,且每隔500ms订阅这个事件,获取input输入的值
public keyword:string;
public searchInput:FormControl=new FormControl(); //创建一个FormControl对象,用于发射valuechange事件来检测被绑定的input的value的变化
constructor(private router:Router,private stockService:StockService) { }
ngOnInit() { //頁面初始化的時候會被調用的方法
this.stocks=this.stockService.getStocks();
this.searchInput.valueChanges
.debounceTime(500).
subscribe(stockName=>
this.keyword=stockName
);
}
思路2实现:
第一步:创建管道 ng g pipe stock/stockFilter,从而创建了StockFilterPipe管道,并将其加入app.module.ts
declarations: [
AppComponent,
StockFilterPipe,
],
第二步:编写管道规则
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'stockFilter'
})
export class StockFilterPipe implements PipeTransform {
//三个参数,list:要过滤的数组; field:根据数组中的哪一个字段过滤 keyword:根据那个值来过滤,输入的关键字
transform(list: any[], field: string,keyword:string): any {
if(!field||!keyword){
return list;
}
return list.filter(
item=>{
let itemFieldValue=item[field].toLowerCase();
return itemFieldValue.indexOf(keyword)>=0;
}
)
}
}
第三步:给股票信息列表应用管道规则
<table class="table table-bordered">
<tr>
<th>#</th>
<th >股票名称</th>
<th>价格</th>
<th>评级</th>
<th >操作</th>
</tr>
<tr *ngFor="let stock of stocks | stockFilter:'name':keyword;let i=index">
<td>{{i+1}}</td>
<td>{{stock.name}}</td>
<td>{{stock.price}}</td>
<td>
<app-stars [rating]="stock.rating"></app-stars>
</td>
<td>
<a class="btn btn-warning btn-xs" href="javascript:;" (click)="update(stock)" ><span class="glyphicon glyphicon-pencil"></span>修改</a>
<a class="btn btn-danger btn-xs" href="#"><span class="glyphicon glyphicon-remove"></span>删除</a>
</td>
</tr>
</table>
导入
ReactiveFormsModule时,必须导入
FormsModule,否则会报错。