You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular表单切换值时展示旧数据问题求助

Angular Mat-Autocomplete 详情更新异常问题

我在Angular项目中使用mat-autocomplete字段,选中选项后会在表单右侧展示该选项详情。但遇到问题:清空当前值后选择新值,详情视图仍显示之前的详情数据,而非新选中值的详情。

现有代码

HTML代码

<mat-form-field class="full-wid mrgn-b-md" appearance="fill">
    <mat-label>{{'Product Name'|translate}}</mat-label>
    <input type="text"
           placeholder="Pick one"
           matInput
           formControlName="gtin"
           [matAutocomplete]="gtin_auto"
    >
    <mat-autocomplete
            autoActiveFirstOption
            #gtin_auto="matAutocomplete"
            [displayWith]="displayFnGTIN"
    >
        <mat-option
                *ngFor="let option of filteredListOfProduct | async"
                [value]="option"
                (onSelectionChange)="onProductChange(option)"
        >
            {{option.brandname_en}}
        </mat-option>
    </mat-autocomplete>
    <button type="button" mat-button *ngIf="form.get('gtin').value" matSuffix mat-icon-button aria-label="Clear"
            (click)="clearGTINOption()">
        <mat-icon>close</mat-icon>
    </button>
</mat-form-field>

TypeScript代码

displayFnGTIN(product: IProduct) {
    console.log('displayFnproduct', product);
    return product && product.brandname_en ? product.brandname_en : '';
}

onProductChange(ob) {
    console.log('Product changed...');
    console.log('Product...',ob);
    console.log('this.selectedProduct    BEFORE',this.selectedProduct);
    this.selectedProduct = ob;
    console.log('this.selectedProduct    AFTER',this.selectedProduct);
}

clearGTINOption() {
    console.log('clearGTINOptions!!!!');
    this.selectedProduct = null;
    this.form.get('gtin').reset();
}

问题原因与解决方案

核心原因

mat-option的onSelectionChange事件会在选项选中和取消选中时都触发,清空操作可能触发该事件传递旧值,导致后续选中新值时出现状态混乱;另外,若selectedProduct的引用未发生变化,Angular变更检测可能未触发视图更新。

修复步骤

  1. 替换事件绑定:将mat-option上的onSelectionChange改为mat-autocomplete的optionSelected事件,该事件仅在用户选中有效选项时触发:
<mat-autocomplete
        autoActiveFirstOption
        #gtin_auto="matAutocomplete"
        [displayWith]="displayFnGTIN"
        (optionSelected)="onProductChange($event.option.value)"
>
    <mat-option
            *ngFor="let option of filteredListOfProduct | async"
            [value]="option"
    >
        {{option.brandname_en}}
    </mat-option>
</mat-autocomplete>
  1. 确保清空操作彻底:在clearGTINOption中明确设置表单控件值为null,避免残留状态:
clearGTINOption() {
    console.log('clearGTINOptions!!!!');
    this.selectedProduct = null;
    this.form.get('gtin').reset(null); // 明确传入null确保值清空
}
  1. 强制触发变更检测(可选):若视图仍未更新,可通过创建新对象实例更新selectedProduct的引用:
onProductChange(ob) {
    console.log('Product changed...');
    console.log('Product...',ob);
    // 创建新对象触发变更检测
    this.selectedProduct = {...ob};
}

内容的提问来源于stack exchange,提问作者ZAJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:02:42