Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically select item in material autocomplete

I have an mat-autocomplete on a page where we store previously used values in localStorage. I need to be able to set the mat-autocomplete value on load if the item exists in localstorage, but am unsure how to do so?

The html of my autocomplete is;

<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>

then the component.ts is;

 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??
            }
        });
}

As I mention in the code the ICategory is a name, id pair. It is also the Id stored in localstorage.

How would I set the value here please?

like image 620
Matthew Flynn Avatar asked Mar 31 '26 23:03

Matthew Flynn


1 Answers

Set the value of your form control, then trigger your search or whatever your autocomplete is supposed to trigger.

let category = localStorage.getItem('trade');
this.tradeCtrl.setValue(category);
// ... Then run your search

EDIT Didn't see the ID/value comment. Here is how to find the correct category

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

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!