Angular 11 中基于首个下拉框联动第二个下拉框失效怎么解决?
问题排查及修复方案
核心问题原因
你代码的核心问题是对Angular Material mat-select 组件的change事件参数理解错误:
原生HTML select的change事件返回的是带target属性的原生事件对象,但mat-select的(change)事件返回的是MatSelectChange类型对象,选中值直接存放在event.value属性中,不存在event.target.value,所以你的取值逻辑直接报错中断,导致states数组没有被赋值。
其他需要排查的前置依赖
- 确认你所在模块的
imports数组中已经导入了FormsModule(支持ngModel双向绑定)、MatSelectModule、MatFormFieldModule、MatInputModule这几个必要依赖 - 确认ts文件中已经声明了
custFirst变量,你当前贴的ts代码里缺失这个绑定变量,也会导致绑定异常
修正后的代码
TS文件修正
Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month'} ] }, { name: '2nd of the month', states: [ {name: '17th of the month'} ] }, { name: '3rd of the month', states: [ {name: '18th of the month'} ] }, ] states: Array<any> = []; cities: Array<any> = []; custFirst: string = ''; // 补上缺失的绑定变量 changeCountry(event: any) { // 直接取event.value,不需要走target,加可选链避免未匹配到值时报错 this.states = this.Countries.find(cntry => cntry.name == event.value)?.states || []; }
HTML文件可选优化
可以直接把change事件的传参改成直接传选中值,不需要传事件对象,写法更直观:
<mat-form-field> <mat-select [(ngModel)]="custFirst" name="custFirst" placeholder="Country" (change)="changeCountry($event.value)"> <mat-option *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option> </mat-select> </mat-form-field> <mat-form-field> <mat-select placeholder="State" [(ngModel)]="custSecond" name="custSecond"> <!-- 建议也给第二个下拉加ngModel绑定方便后续取值 --> <mat-option *ngFor="let state of states" [value]="state.name">{{ state.name }} </mat-option> </mat-select> </mat-form-field>
效果参考

内容的提问来源于stack exchange,提问作者Mohamed Irshath
相关产品推荐
相关产品推荐

