Búsqueda de sitios web

javascript - Angular no vuelve a renderizar la vista después de que cambia el valor del modelo relacionado


Estoy haciendo una aplicación simple de Angular, tengo 2 modelos a continuación

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;
}

y

class Brand implements IBrand {

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

Entonces la relación es que el Cliente tiene 1 marca (almacenada como id de marca)

entonces, en la vista de gestión de clientes tengo una tabla que muestra el nombre de la marca y utilizo un modal de ngBootstrap para la vista de actualización

Entonces, el problema es que después de actualizar la marca en el modal, descubrí que la tabla de clientes no se actualizó, todavía tiene el valor anterior. ¿Cómo corrijo este valor?

Aquí algunos de mis 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();
    });
  }

y aquí algunos de mis customer-row.component.html

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

Respuesta #1

Esto puede que no resuelva el problema, pero intenta asignar las variables a nuevas ubicaciones en la memoria para que se produzca la detección de cambios.

Prueba esto:

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) };
  }

Respuesta #2

Resuelvo el problema implementando el código ngOnChanges a continuación

  ngOnChanges(changes: SimpleChanges): void {
    this.setBrand();
    this.setLogistic();
  }

No estoy seguro de que esta sea la manera correcta, pero puede resolver mi problema