简体   繁体   中英

Angular not re-render view after relate model value change

I'm make simple angular app I have 2 model below

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

and

class Brand implements IBrand {

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

So relation is Customer has 1 brand (store as brand id)

then in customer management view I have table that show brand's name and I use ngBootstrap modal for update view

So, the problem is after I update brand on modal I found the customer table not updated it's still previous value How I correct this value

Here some my 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();
    });
  }

and here some my customer-row.component.html

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

This may not solve the problem but try assigning the variables to new locations in memory so change detection takes place.

Try this:

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

I solve problem by implement ngOnChanges code below

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

I'm not sure this is a correct way but it's can solve my problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM