这是一个实际开发过程中,可能经常会遇到的场景,有以下两个要点。
要点:
1、前台input控件绑定到后台FormControl类型变量,进入观察者模式
2、使用管道动态筛选搜索结果
步骤一:组件所属模块中,申明import:ReactiveFormControl,declarations:FilterPipe
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import ...
import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {FilterPipe} from '../../pipe/filter.pipe';
@NgModule({
imports: [
...
ReactiveFormsModule
],
declarations: [
...
FilterPipe
],
providers: [
...
]
})
export class TaskModule {
}
步骤二:写好过滤器管道代码
//这个管道有单个参数:list(被筛选对象列表)、field(筛选的字段)、keyword(筛选关键字)
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(list: Array<any>, field: string, keyword: string): any {
if (!field || !keyword) {
return list;
}
return list.filter(item => {
return item[field].indexOf(keyword) >= 0;
});
}
}
步骤四:前端绑定input控件,写好管道
<!--将searchInput注册到formControl容器中,后台有对应的变量对接-->
<input type="text" name="table_search" class="form-control pull-right" placeholder="搜索"
[formControl]="searchInput">
<table class="table table-bordered">
<tbody>
<tr>
<th class="text-center" style="width: 10px">#</th>
<th class="text-center">标题</th>
<th class="text-center" style="width: 100px">负责人</th>
<th class="text-center" style="width: 200px">学校</th>
<th class="text-center" style="width: 100px">紧急程度</th>
<th class="text-center" style="width: 100px">操作</th>
</tr>
<tr *ngFor="let item of tasks|filter:'title':keyword;let i=index">
<td>{{item.id}}</td>
<td><a href="javascript:;" (click)="OpenUrl(item.id)">{{item.title}}</a></td>
<td class="text-center">{{item.fuzeren}}</td>
<td>{{item.schoolname}}</td>
<td><span class="badge bg-green">重要紧急</span></td>
<td class="text-center">
<a href="javascript:;">编辑</a>
<a href="javascript:;">删除</a>
</td>
</tr>
</tbody>
</table>
步骤五:后台ts代码
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {TaskService} from '../../../service/task.service';
import {FormControl} from '@angular/forms';
import 'rxjs/Rx';
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
private tasks = [];
private keyword:string;
private searchInput: FormControl = new FormControl();
constructor(private router: Router, private taskService: TaskService) {
this.tasks = this.taskService.GetTasks();
//valueChanges是观察者对象类型
this.searchInput.valueChanges
.debounceTime(500)
.subscribe(
e => {
this.keyword = e;
}
);
}
ngOnInit() {
}
OpenUrl(id) {
this.router.navigate(['/main/task/detail', id]);
}
}
最终效果Gif:
GIF.gif
网友评论