我想使用角度/角度材料自动完成组件来过滤数千个字符串。我要提取大约12k项的数组,并且要过滤可能包含用户键入但按任何特定顺序的所有字符串的项。这是我的组件代码的外观:
import {Component, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import { DatabaseService } from '../database.service';
import { FormControl } from '@angular/forms';
import {Observable } from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'app-search-item',
templateUrl: './search-item.component.html',
styleUrls: ['./search-item.component.css']
})
export class SearchItemComponent implements OnInit, OnDestroy {
private selectedItemDescription: string;
itemFormControl = new FormControl();
selectedItemNumber: string;
itemOptions = [];
setItemOptions: any;
itemDescriptionMatches: Observable<string[]>;
constructor(private db: DatabaseService) {
}
ngOnInit() {
console.log('Getting data.');
this.db.cnxn.openDb('mydb');
this.db.cnxn.select({
from: 'items',
})
.then((results) => {
for (const item of results) {
this.itemOptions.push(item['desc']);
}
})
.catch((error) => {
});
this.itemDescriptionMatches = this.itemFormControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toUpperCase().split(' ');
// return filterValue.filter(el => this.setItemOptions.has(el));
return this.itemOptions.filter(option => option.includes(filterValue));
// return this.setItemOptions.has(itemOption => filterValue.map(itemOption.includes));
}
ngOnDestroy() {
this.itemOptions = [];
}
closeDialog() {
}
}
我的主要问题是:是否可以将此查询存储在组件文档中的变量中,使其只需要在后台运行一次即可,然后每当它们打开对话框时,它便会自动捕获该数组变量并将其用作自动完成列表的选项,是否有可能将过滤器加速到用户输入完毕后不需要花费太多时间来加载过滤结果的地方?
我的模板如下:
<div>
<mat-form-field>
<mat-label>Item Description</mat-label>
<input matInput type="text" placeholder="Type an item description"
[matAutocomplete]="auto" [formControl]="itemFormControl" id="itemInput">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let option of itemDescriptionMatches | async" [value]="option" (onSelectionChange)="lookupItemNumber()">
{{ option }}
</mat-option>
</mat-autocomplete>
</div>
我知道我必须实现某种反跳功能,以等待用户停止键入一定的毫秒数才能运行该功能,但我只是不知道该如何实现。另外,是否有比我目前使用_filter方法更快的方法来过滤字符串?