如何在Angular 5 Material Autocomplete中设置默认选中值?
Hey there! I totally get the confusion—looking for a selected attribute on mat-option and coming up empty can be frustrating. Let me break down how to set a default selected value properly with Angular Material, since it works a bit differently than you might expect.
The Key Idea: Bind to a Form Control (or ngModel)
Angular Material's autocomplete doesn't rely on a direct selected attribute on mat-option. Instead, it ties the selected state to the value of the associated form control. Here's how to implement it:
1. Using FormControl (Reactive Forms)
First, set up a FormControl in your component and initialize it with your default value (make sure this value matches the [value] you've set on mat-option—in your case, that's srd2.itemCode):
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; @Component({ // Your component metadata here }) export class YourComponent implements OnInit { myControl = new FormControl(); stockreqDetailItemList = [/* Your existing list of items */]; ngOnInit(): void { // Replace with your actual default itemCode from the list const defaultItemCode = 'ABC123'; this.myControl.setValue(defaultItemCode); } }
Then update your template to bind the input to this FormControl:
<input type="text" [formControl]="myControl" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let srd2 of stockreqDetailItemList" [value]="srd2.itemCode"> {{srd2.itemCode}} {{srd2.itemName}} </mat-option> </mat-autocomplete>
2. Using ngModel (Template-Driven Forms)
If you're using template-driven forms instead, you can bind to a component property directly:
import { Component } from '@angular/core'; @Component({ // Your component metadata here }) export class YourComponent { selectedItemCode = 'ABC123'; // Default itemCode from your list stockreqDetailItemList = [/* Your existing list of items */]; }
Update the template to use two-way binding with ngModel:
<input type="text" [(ngModel)]="selectedItemCode" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let srd2 of stockreqDetailItemList" [value]="srd2.itemCode"> {{srd2.itemCode}} {{srd2.itemName}} </mat-option> </mat-autocomplete>
Important Note
Make sure your default itemCode actually exists in stockreqDetailItemList. If the value doesn't match any option's [value], the autocomplete won't display a selected state.
The reason you won't find a selected attribute in the mat-option docs is because Angular Material manages selection through the form control binding—this keeps your form state consistent and aligned with Angular's form patterns.
内容的提问来源于stack exchange,提问作者ToldarkenHansam

