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

保存Modal表单后刷新Select下拉菜单的实现方案

解决方案:无刷新更新产品下拉选项

步骤1:修改模态框组件,传递新创建的产品

在AddProductComponent的save方法中,关闭模态框时将新创建的产品实例传递给父组件:

save() {
    const product: any = {};
    Object.assign(product, this.productForm.value);
    this.id = this.route.snapshot.params['id'];
    this.isAddMode = !this.id;
    if (!this.isAddMode) {
        this.productService.updateProduct(this.id, product).subscribe(product => {
                this.router.navigate(["products"]);               
        });
    } else {
        this.productService.saveProduct(product).subscribe(product => {
            if (product != null) {
                 // 关闭模态框时传回新创建的产品
                 this.activeModal.close(product); 
            } else {
                // 错误处理逻辑
            }
        });
    }
}

步骤2:在父组件监听模态框关闭事件,更新产品列表

修改AddServiceRecordsComponent中的openModalAddProduct方法,订阅模态框的关闭事件,拿到新产品后更新下拉选项的数据源,保持原有排序:

openModalAddProduct() {
    const modalRef = this.modalService.open(AddProductComponent);
    // 监听模态框关闭事件,接收返回的新产品
    modalRef.closed.subscribe((newProduct: Product) => {
        if (newProduct) {
            // 方式一:直接添加新产品并重新排序(性能更好)
            this.products.push(newProduct);
            this.products.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
            
            // 方式二:重新从接口拉取完整产品列表(适用于需要同步其他修改的场景)
            // this.productService.getProducts().subscribe(products => {
            //     this.products = products;
            //     this.products.sort((a, b) => a.name.toLowerCase().localeCompare(b.name.toLowerCase()));
            // });
        }
    });
}

说明

  • 方式一适合仅添加单个产品的场景,无需再次请求接口,响应更快
  • 方式二更可靠,能确保产品列表与后端完全同步,适合有多个地方修改产品数据的场景
  • 由于下拉框使用了[compareWith]="compareObjectProduct",只要新产品的结构与现有产品一致,就能正常选中匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:05:57