Angular Mat-Autocomplete输入匹配内容不显示选项问题求助
修复Mat-Autocomplete不显示选项的问题
核心问题及修复步骤:
输入框未与自动完成组件绑定
Mat-Autocomplete要求输入框通过[matAutocomplete]属性关联到对应的<mat-autocomplete>组件,否则下拉面板无法触发显示。修改HTML中的input标签:<input matInput [formControl]="companyConnectwiseNameControl" [matAutocomplete]="auto" autocomplete="off">移除重复的API请求
filterOptions方法中两次调用getConnectwiseCompanies(),还额外添加了不必要的subscribe,这会造成重复请求且浪费资源。简化方法逻辑:filterOptions(value: string): Observable<ConnectwiseCompany[]> { const filterValue = value.toLowerCase(); return this.connectwiseService.getConnectwiseCompanies().pipe( map(companies => companies.filter(company => company.name.toLowerCase().includes(filterValue) )) ); }(如果需要调试打印,直接在map里处理即可,无需单独subscribe)
调整初始值匹配逻辑(可选)
当前ngOnInit中设置的是connectWiseId,但过滤逻辑基于公司名称。如果connectWiseId不是名称的一部分,初始状态下filteredOptions会是空数组。如果需要预填公司名称,应改为设置对应的name字段:ngOnInit(): void { if (this.data && !this.data.isNewCompany) { // 替换为实际的公司名称字段 this.companyConnectwiseNameControl.setValue(this.data.company.connectWiseName); } this.filteredOptions = this.companyConnectwiseNameControl.valueChanges.pipe( startWith(''), switchMap(value => this.filterOptions(value)) ); }
修改后的完整代码
组件TS:
companyConnectwiseNameControl = new FormControl(); filteredOptions: Observable<ConnectwiseCompany[]>; constructor( private dialogRef: MatDialogRef<CompanyModalComponent>, @Inject(MAT_DIALOG_DATA) public data: { company: CompanyConnection, isNewCompany: boolean }, private connectwiseService: ConnectwiseService ) {} ngOnInit(): void { if (this.data && !this.data.isNewCompany) { // 预填公司名称而非ID this.companyConnectwiseNameControl.setValue(this.data.company.connectWiseName); } this.filteredOptions = this.companyConnectwiseNameControl.valueChanges.pipe( startWith(''), switchMap(value => this.filterOptions(value)) ); } filterOptions(value: string): Observable<ConnectwiseCompany[]> { const filterValue = value.toLowerCase(); return this.connectwiseService.getConnectwiseCompanies().pipe( map(companies => companies.filter(company => company.name.toLowerCase().includes(filterValue) )) ); }
组件HTML:
<div mat-dialog-content class="dialog-content"> <h2>Edit Company Connection</h2> <h1>Datto Domain: {{ data.company.dattoDomain }}</h1> <mat-form-field> <mat-label>ConnectWise Company Name</mat-label> <input matInput [formControl]="companyConnectwiseNameControl" [matAutocomplete]="auto" autocomplete="off"> <mat-autocomplete #auto="matAutocomplete"> <mat-option *ngFor="let option of filteredOptions | async"> {{ option.name }} </mat-option> </mat-autocomplete> </mat-form-field> </div> <div> <div *ngFor="let option of filteredOptions | async"> {{ option.name }} </div> </div> <div mat-dialog-actions> <div style="margin-left: auto"> <button mat-button class="cancel" (click)="cancel()">Cancel</button> <button mat-button [disabled]="!formValid()" (click)="save()">Save</button> </div> </div>
内容的提问来源于stack exchange,提问作者Hayden Key
相关产品推荐
相关产品推荐

