首页 > 解决方案 > 相关模型值更改后角度不重新渲染视图

问题描述

我正在制作简单的角度应用程序,下面有 2 个模型

class Customer implements ICustomer
{
    id?: number | null | undefined;
    name: string | null;
    addr: string | null;
    tel: string | null;
    postCode: string | null;
    defaultBrand: number | null;
    defaultLogistic: number | null;
    createdOn: string | null;
    updatedOn: string | null;
}

class Brand implements IBrand {

  id?: number | undefined;
  name: string = "";
  shortName: string = "";
  imgPath: string = "";
  isEnable?: boolean | undefined = false;
  createdOn: string = "";
  updatedOn: string = "";
}

所以关系是客户有 1 个品牌(存储为品牌 ID)

然后在客户管理视图中,我有显示品牌名称的表格,我使用 ngBootstrap 模式进行更新视图

所以,问题是我在模态上更新品牌后发现客户表没有更新它仍然是以前的值我如何更正这个值

这里有一些我的customer-row.component.ts

  ngOnInit(): void {
    this.setBrand();
    this.setLogistic();
  }

  setBrand(): void {
    this.brand = this.brandService.brandList.find(x => x.id === this.item.defaultBrand);
  }

  setLogistic(): void {
    this.logistic = this.logisticService.LogicticList.find(x => x.id === this.item.defaultLogistic);
  }

  onEditClick(): void {
    this.modalRef = this.modal.open(CustomerModalUpdateComponent, {
      animation: true,
      size: 'xl',
      backdrop: 'static'
    });
    this.modalRef.componentInstance.title = `${this.item.name}`;
    this.modalRef.componentInstance.item = this.item;
    this.modalRef.closed.subscribe((result:any) => {
      this.setBrand();
      this.setLogistic();
      this.changeDetectRef.detectChanges();
    });
  }

这里有一些我的customer-row.component.html

 <td class="text-center">
    {{ this.brand?.name }}
  </td>
  <td class="text-center">
    {{ this.logistic?.name }}
  </td>

标签: javascriptangulartypescript

解决方案


这可能无法解决问题,但尝试将变量分配到内存中的新位置,以便进行更改检测。

试试这个:

setBrand(): void {
    this.brand = { ...this.brandService.brandList.find(x => x.id === this.item.defaultBrand) };
  }

  setLogistic(): void {
    this.logistic = { ...this.logisticService.LogicticList.find(x => x.id === this.item.defaultLogistic) };
  }

推荐阅读