首页 > 解决方案 > Prime ng 表在第一次更改时未更新

问题描述

我有一个主要的商店表,我可以在其中删除商店并将其添加到列表中。

行为:当添加商店时,ChildComponent会发出一个事件ParentComponent,然后将商店添加到列表中并更新输入的可观察对象,ChildComponent以便商店不再出现在表中。

问题:上述行为正常工作,除非表格被过滤,然后在添加商店时表格没有更新,即使我可以看到表格数组已在组件中正确更新。但是,当添加另一个商店(在同一个过滤表中)时,它工作正常,然后两个商店都从表中删除。

该表是纯组件(子)的一部分:


export class ChildComponent implements OnInit {
  @Input() shops$: BehaviorSubject<Shop[]>
  @Output() addSelectedShops = new EventEmitter<Shop[]>()
  shops: Shop[]
  selectedShops: Shop[] = []

  constructor() {}

  ngOnInit(): void {
     this.shops$.subscribe((data) => {
          this.shops = data
        })
  }

 // this is called when adding a new shop
  onAddSelectedShops(): void {
    this.addSelectedShops.emit(this.selectedShops)
    this.selectedShops = []
  }
}

带有 update 方法的父组件:


export class ParentComponent implements OnInit {
  shops$: BehaviorSubject<Shop[]>
  localShops: Shop[]
  list: Shop[]

  constructor() {}

  ngOnInit(): void {
   // localShops is initiated here
}

// this is called via the event emitter
  addShopToList(shop: Shop): void {
    this.list.push(shop)
    const shopIndex = this.localShops.findIndex(...)
    if (shopIndex > -1) {
      this.localShops.splice(shopIndex, 1)
    }
    this.shops$.next(this.localShops)
  }
}

这是 childComponent 中的表:

 <p-table #dt1 [value]="shops" [(selection)]="selectedShops" [globalFilterFields]="['resellerName']" dataKey="uniqueResellerName">
   <ng-template pTemplate="caption">
      <span>
         <i class="candidate-shop-list__search-bar-icon pi pi-search"></i>
         <input pInputText type="text" (input)="dt1.filterGlobal($any($event.target).value, 'contains')"                               placeholder="Search" />
      </span>
   </ng-template>
   <ng-template pTemplate="header">
                    ..... HEADERS ....
   </ng-template>
   <ng-template pTemplate="body" let-rowIndex="rowIndex" let-shop>
                 ..... DATA  ....
   </ng-template>
</p-table>

请让我知道是否有任何想法为什么这不适用于第一次添加。谢谢你。

标签: angularprimengp-table

解决方案


我遵循了这个问题的答案,它对我有用,但我仍然不完全理解为什么它在第一次添加时不起作用,然后在之前的下一个添加中起作用。


推荐阅读