我目前正在开发一个搜索栏组件。使用自定义管道,我可以显示项目的下拉列表。我需要将筛选后的项目列表(items|CustomPipe:search_input(从searchbar.component.html传递到searchbar.comcomponent.ts,但我不确定如何
searchbar.component.html
<ul *ngIf="(Items | CustomPipe : search_input).length>0" class="list-group dropdown-container">
<li *ngFor="let item of Items | CustomPipe : search_input; index as i" [class.active]="i == arrowkeyLocation" (mouseover)=changeStyle($event)
(mouseleave)=changeStyle($event) (click)="showConfirm(item)" class="list-group-item" [innerHTML]="item.model | highlight : search_input"></li>
</ul>
我目前的方法:
<input #filterSize type="hidden" value="{{(Items | CustomPipe : search_input).length}}">
<input #filterContent type="hidden" value="{{(Items | CustomPipe : search_input)}}">
searchbar.component.ts
export class SearchbarComponent implements OnInit {
arrowkeyLocation: number = 0;
@ViewChild('filterSize') filterSize: any;
@ViewChild('filterContent') filterContent: any;
@Output() onSelect: EventEmitter<number> = new EventEmitter<number>();
constructor() {
}
ngOnInit() { }
changeStyle(event) {
let content = this.filterContent.nativeElement.value;
let dropdownSize = this.filterSize.nativeElement.value;
if (event.type == "keydown") {
switch (event.keyCode) {
case 38: // this is the ascii of arrow up
if (this.arrowkeyLocation == -1) {
this.arrowkeyLocation = dropdownSize;
}
this.arrowkeyLocation--;
break;
case 40: // this is the ascii of arrow down
if (this.arrowkeyLocation == dropdownSize) {
this.arrowkeyLocation = -1;
}
this.arrowkeyLocation++;
break;
case 13:
this.onSelect.emit(content[this.arrowkeyLocation]);
break;
}
}
}
但是,我无法正确检索对象列表(内容变量(。它作为[object object]的字符串值从html传递到组件。有人可以建议解决这个问题吗?
我可以为此提供解决方案。
- 使用一个普通的实用程序函数,并在该函数中实现过滤器逻辑
- 按键事件时,从searchbar.component.ts调用该函数并填充过滤内容
- 然后根据需要使用searchbar.component.ts中的过滤内容
- 也可以在searchbar.component.html中使用过滤内容
示例: [这不是真正的代码]
searchbar.component.ts
KeyPressCallback(search_input) {
this.filteredContent = utilityFunctionToFilter(Items, search_input);
// Do whatever you like with filteredContent.
}
searchbar.component.html
<ul *ngIf="filteredContent.length>0" class="lis ...