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

标签 angular angular-material

我在一个页面上有一个 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/

相关文章:

javascript - 如何使用拓扑图处理 Cytoscape.js Canvas 上的鼠标滚动和按键事件

javascript - Angular 5 : Difference between console and template

Angularfire2读取数据一次

javascript - 如何以编程方式更改 Material Calendar <mat-calendar> 中的月份

angular - 从 Angular 中的 Modal 路由到其他页面

javascript - Karma 没有存储提供程序,但已添加

javascript - 密码确认 Angular Material

css - 如何更改 md-select 上的标签颜色

css - Mat-Stepper - 将特定步骤更改为点

angularjs - Angular Material 对话框 : Set focus on the first item