Angular中选择mat-autocomplete后无法更新mat-option的问题
问题修复方案
1. 组件方法变量错误
你的selectedCustomer方法里使用了未定义的变量a,需要替换为声明好的numbers:
selectedCustomer(option: MatOption) { const numbers = ['one', 'two', 'three']; this.customerAccounts = [...numbers]; // 将a改为numbers }
2. 模板结构与语法错误
mat-option必须嵌套在mat-select或mat-autocomplete容器内,直接放在div中无法被Angular Material识别为下拉选项,第二个下拉需要用mat-select包裹:
<mat-form-field class="example-full-width"> <mat-label>Account</mat-label> <mat-select> <mat-option *ngFor="let accountId of customerAccounts" [value]="accountId"> {{accountId}} </mat-option> </mat-select> </mat-form-field>
mat-autocomplete的optionSelected事件绑定缺少闭合引号和括号,修正为:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedCustomer($event.option)">
3. 移除表单绑定冲突
Angular不建议同时使用[(ngModel)]和formControlName,会导致表单状态异常,建议移除[(ngModel)],直接通过表单控件管理输入值:
<input type="text" matInput [formControlName]="input" [matAutocomplete]="auto">
完整修正代码示例
模板代码
<mat-form-field class="example-full-width"> <mat-label>Number</mat-label> <input type="text" matInput [formControlName]="input" [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete" (optionSelected)="selectedCustomer($event.option)"> <mat-option *ngFor="let option of filteredOptions" [value]="option"> {{option}} </mat-option> </mat-autocomplete> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Account</mat-label> <mat-select> <mat-option *ngFor="let accountId of customerAccounts" [value]="accountId"> {{accountId}} </mat-option> </mat-select> </mat-form-field>
组件方法
selectedCustomer(option: MatOption) { const numbers = ['one', 'two', 'three']; this.customerAccounts = [...numbers]; }
内容的提问来源于stack exchange,提问作者Melih
相关产品推荐
相关产品推荐

