我在页面上有一个mat-autocomplete
,我们将之前使用的值存储在localStorage中。如果项目存在于localstorage中,我需要能够在加载时设置mat-autocomplete
值,但我不确定该怎么做?
我的自动填充功能的html是;
<input type="text" placeholder="Select a trade" aria-label="Select a trade" matInput [formControl]="tradeCtrl" [matAutocomplete]="auto" required>
<mat-error *ngIf="tradeCtrl.invalid">You must enter a trade.</mat-error>
<mat-autocomplete #auto="matAutocomplete" md-menu-class="autocomplete">
<mat-option *ngFor="let option of filteredCategoryOptions | async" [value]="option.name" (onSelectionChange)="onTradeSelected($event, option)">
<span [innerHTML]="option.name | highlight: toHighlight"></span>
</mat-option>
</mat-autocomplete>
然后component.ts是;
ngOnInit() {
this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
this.categoryOptions = categories;
this.filteredCategoryOptions = this.tradeCtrl.valueChanges
.pipe(
startWith(''),
map(options => options ? this.categoryFilter(options) : this.categoryOptions.slice())
);
//bool whether we populate from localStorage or not
if (this.populateOnInit) {
let category = localStorage.getItem('trade');
// note that this will be the TradeCategory.Id
//how to set the autocomplete here??
}
});
}
正如我在代码中提到的,ICategory是一个名称,id对。它也是存储在localstorage中的Id。
我如何在这里设定价值?
答案 0 :(得分:2)
设置表单控件的值,然后触发搜索或自动填充应该触发的任何内容。
let category = localStorage.getItem('trade');
this.tradeCtrl.setValue(category);
// ... Then run your search
编辑没有看到ID /值评论。以下是如何找到正确的类别
const categoryID = localStorage.getItem('trade');
const category = categories.find(c => c.id === categoryID); // Parse to Number if not a string
this.tradeCtrl.setValue(category);
// ... Then run your search
答案 1 :(得分:0)
如何创建方法
resetAutoComplete(){
this.filteredCategoryOptions = this.tradeCtrl.valueChanges
.pipe(
startWith(''),
map(options => options ? this.categoryFilter(options) : this.categoryOptions.slice())
);
}
然后将其称为
ngOnInit() {
this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
this.categoryOptions = categories;
this.resetAutoComplete();
//bool whether we populate from localStorage or not
if (this.populateOnInit) {
const categoryID = localStorage.getItem('trade');
this.categoryOptions = categories.find(c => c.id === categoryID);
this.resetAutoComplete();
}
});
}