Angular MatAutocomplete筛选功能实现报错求助
问题:Angular MatAutocomplete筛选失效及
Cannot read properties of null (reading 'dispose')报错 我从API获取州名数据,已成功加载到MatAutocomplete下拉框,但无法实现官方示例中的筛选功能,同时出现客户端错误:ERROR TypeError: Cannot read properties of null (reading 'dispose')
报错指向<mat-option *ngFor="let st of stateListn | async">行。
相关代码及API响应
HTML代码
<mat-form-field class="full-width"> <mat-label>State</mat-label> <input type="text" matInput formControlName="state" required [matAutocomplete]="auto"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let st of stateListn | async" [value]="st.state" class="mat-option2"> {{st.state}} </mat-option> </mat-autocomplete> </mat-form-field> <small *ngIf="AddShipperForm.controls['state'].hasError('required') && AddShipperForm.controls['state'].touched" class="form-error-msg"> State Name is required </small>
TypeScript代码
ngOnInit() { this.userDetails = this.userService.getUserDetails() this.createAddShipperForm(); this.getStatelist(); this.materialtypelist(); this.st = this.AddShipperForm.get('state').valueChanges.pipe( startWith(''), map(value => this._filter(value || '')), ); } _filter(value: string): string[] { const filterValue = value.toLowerCase(); return this.options.filter(option => option.toLowerCase().includes(filterValue)); } getStatelist() { this.api.get('customer/getStateList').subscribe(response => { this.responsedata = response; if (this.responsedata.success == "true") { this.stateList = this.responsedata.data; this.stateListn = this.stateList; for (let i = 0; i < this.stateListn.length; i++){ this.options.push(this.stateListn[i]); } this.st = of(this.Options); } if (this.responsedata.success == "false") { this.confirmServicenew.confirm({ title: this.responsedata.message }).subscribe(res => {}); } }); }
API响应
{"data":[{"state":"KARNATAKA"},{"state":"DAMAN AND DIU"},{"state":"DELHI"},{"state":"RAJASTHAN"},{"state":"MANIPUR"},{"state":"WEST BENGAL"},{"state":"ANDHRA PRADESH"},{"state":"MADHYA PRADESH"},{"state":"KERALA"},{"state":"TELANGANA"},{"state":"GUJARAT"},{"state":"BIHAR"},{"state":"CHANDIGARH"},{"state":"GOA"},{"state":"TRIPURA"},{"state":"DADRA AND NAGAR HAVELI"},{"state":"NAGALAND"},{"state":"ASSAM"},{"state":"JHARKHAND"},{"state":"PUNJAB"},{"state":"JAMMU AND KASHMIR"},{"state":"PUDUCHERRY"},{"state":"ANDAMAN AND NICOBAR ISLANDS"},{"state":"MEGHALAYA"},{"state":"MIZORAM"},{"state":"MAHARASHTRA"},{"state":"ARUNACHAL PRADESH"},{"state":"CHHATTISGARH"},{"state":"TAMIL NADU"},{"state":"SIKKIM"},{"state":"LAKSHADWEEP"},{"state":"HARYANA"},{"state":"UTTARAKHAND"},{"state":"UTTAR PRADESH"},{"state":"HIMACHAL PRADESH"},{"state":"ORISSA"},{"state":"RAJASTH"}],"success":"true"}
客户端错误信息
ERROR TypeError: Cannot read properties of null (reading 'dispose') <mat-option *ngFor="let st of stateListn | async" <--- ERROR
解决方案
1. 修复async管道报错问题
stateListn是直接赋值的数组,不是Observable类型,不能使用async管道。模板中应该绑定你定义的st Observable(用于监听输入变化并返回筛选结果)。
修改模板中的*ngFor:
<mat-option *ngFor="let st of st | async" [value]="st.state" class="mat-option2"> {{st.state}} </mat-option>
2. 修正数据处理与筛选逻辑
- API返回的是包含
state属性的对象数组,你之前错误地将整个对象推入options数组,而非state字符串,导致筛选逻辑失效。 - 需要先加载完API数据,再初始化
stObservable,避免覆盖输入监听逻辑。
修改TypeScript代码:
// 定义类型与变量 interface State { state: string; } allStates: State[] = []; st!: Observable<State[]>; ngOnInit() { this.userDetails = this.userService.getUserDetails() this.createAddShipperForm(); this.getStatelist(); this.materialtypelist(); } getStatelist() { this.api.get('customer/getStateList').subscribe(response => { this.responsedata = response; if (this.responsedata.success == "true") { this.allStates = this.responsedata.data; // 初始化筛选Observable,监听输入变化 this.st = this.AddShipperForm.get('state')!.valueChanges.pipe( startWith(''), map(value => this._filter(value || '')) ); } if (this.responsedata.success == "false") { this.confirmServicenew.confirm({ title: this.responsedata.message }).subscribe(res => {}); } }); } _filter(value: string): State[] { const filterValue = value.toLowerCase(); // 针对对象的state属性进行筛选 return this.allStates.filter(item => item.state.toLowerCase().includes(filterValue)); }
3. 额外优化建议
- 使用
!或可选链操作符处理表单控件的null情况,避免潜在报错。 - 确保变量类型明确,提升代码可读性与可维护性。
内容的提问来源于stack exchange,提问作者shan2batman
相关产品推荐
相关产品推荐

