我有一个带搜索功能的下拉菜单和一个带项目的列表(和复选框)我想让searchterm更新该列表中的项目。
示例:
我有5个项目: - project1 - 土豆 - listItem1 - listItem2 - 无论
这个想法是当你没有输入任何你看到所有5个项目的东西时,如果你输入“p”,你只能看到project1和马铃薯。到目前为止,这是我的代码:
<div id="dropdown-menu">
<button id="show-users" (click)="showMenu = !showMenu">Project toevoegen</button>
<div id="drp-project-select">
<div class="scroller" [hidden]="!showMenu">
<div id="search-wrapper">
<i class="fa fa-search"></i>
<input [(ngModel)]="searchTerm" type="text" placeholder="Zoek op naam..." >
</div>
<ul>
<li *ngFor="#project of projectdata.LoginResponse?.ProjectVM, #i = index">
<label class="checkbox-label" >
<input type="checkbox" class="dropdown-checkbox" [(ngModel)]="project.isChecked" >
<span>{{project.Project}}</span>
</label>
</li>
</ul>
</div>
</div>
</div>
答案 0 :(得分:1)
使用过滤管。 有关完整示例,请参阅https://plnkr.co/edit/4Il8QMlh9UYQ4hyrnU3W?p=preview
<input [(ngModel)]="searchTerm" type="text" placeholder="Zoek op naam..." #search>
...
<li *ngFor="#project of projectdata.LoginResponse?.ProjectVM | filter:'Project':search.value, #i = index">
仅支持按一列过滤,但不应该难以扩展。 如果没有要防止
的更改,它会返回相同的结果EXCEPTION:检查后表情发生了变化。
import {Pipe, PipeTransform} from 'angular2/core'
@Pipe({name: 'filter'})
export class FilterPipe implements PipeTransform {
previousResult:any[];
transform(value:any[], args:string[]) : any {
if(!value || !args || args.length < 2 || !args[0] || !args[1]) {
return value;
}
console.log('value: ' + value);
console.log('args: ' + args);
var result = value.filter((val) => {
console.log('item: ' + val[args[0]])
var contains = val[args[0]].indexOf(args[1]) > -1;
console.log('found: ' + contains);
return contains;
});
console.log(result);
if(this.previousResult && this.previousResult.length == result.length) {
for(var i = 0; i < result.length; i++) {
if(this.previousResult[i] != result[i]) {
console.log(i);
this.previousResult = result;
return this.previousResult;
}
}
}
this.previousResult = result;
return this.previousResult;
}
}
答案 1 :(得分:1)
您可以利用表单控件来执行此操作:
constructor() {
this.ctrl = new Control();
// Some data for testing
this.showMenu = true;
this.projectdata = {
LoginResponse: {
ProjectVM: [{
isChecked: true,
Project: 'test'
}]
}
};
this.initialData = this.projectdata.LoginResponse.ProjectVM
this.filteredData = this.initialData.slice(0, 5);
this.ctrl.valueChanges.subscribe(
(val) => {
if (!val) {
this.filteredData = this.initialData.slice(0, 5);
}
this.filteredData = this.initialData.filter((project) => {
return new RegExp('^'+val).test(project.Project);
});
});
}
不要忘记在输入中引用控件:
<input [ngFormControl]="ctrl" type="text" placeholder="Zoek op naam..." >
请参阅此plunkr:https://plnkr.co/edit/ocgXxAvcPPtvW5SXEDQ9?p=preview。