angularprimengp-table

Prime ng table not updating on first change


I have a prime-ng table of shops, where I can remove and add shops to a list.

The behavior: When a shop is added, the ChildComponent emits an event to ParentComponent which then adds the shop to the list and updates the input observable of the ChildComponent so that the shop no longer appears in the table.

The issue: The above behavior works fine except when the table is filtered, then when adding a shop the table is not updated even though I can see that the table array has been updated correctly in the component. However, when another shop is added (in the same filtered table) it works fine, and then both shops are removed from the table.

The table is part of a pure component (child):


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

The parent component with the update method:


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

This is the table in the 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>

Please let me know if there is any idea on why this is not working on the first addition. Thank you.


Solution

  • I followed the answer in this question and it worked for me, but I still don't fully understand why it didn't work on first addition then it worked on the next ones previously.