Prime ng 表不会在第一次更改时更新

时间:2021-06-07 15:15:24

标签: angular primeng p-table

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

行为:当添加商店时,ChildComponentParentComponent 发出一个事件,然后将商店添加到列表中并更新 { {1}} 以便商店不再出现在表格中。

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

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

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 = []
  }
}

这是 childComponent 中的表:


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

如果有任何关于为什么第一次添加不起作用的想法,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:0)

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