gpt4 book ai didi

angular - 以编程方式选择 Material 自动完成中的项目

转载 作者:行者123 更新时间:2023-12-04 01:57:09 24 4
gpt4 key购买 nike

我在一个页面上有一个 mat-autocomplete,我们将以前使用的值存储在 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。

请问我如何设置这里的值?

最佳答案

设置您的表单控件的值,然后触发您的搜索或您的自动完成应该触发的任何内容。

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

关于angular - 以编程方式选择 Material 自动完成中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49774739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com