By Paul Meems


2017-03-03 19:59:15 8 Comments

Using Angular v2.4.8 and PrimeNg v1.1.4

I have a page with two components:

  1. Dropzone, for uploading files
  2. p-datatable to show the uploaded files

I configured Dropzone to send 5 files at a time and when it is finished with 5 files the event onDropZoneSendingMultiple is raised. When all files are uploaded onDropZoneQueueComplete is raised.

In both listeners I want to refresh the datatable which is in the second component. This is not working. I need to refresh the page to see the new files.

My HTML of the main page:

<div class="row" id="dropzoneContainer">
    <dropzone class="dropzone" #dz [config]="dropZoneConfig" 
              (error)="onDropZoneUploadError($event)"
              (sendingmultiple)="onDropZoneSendingMultiple($event)"
              (queuecomplete)="onDropZoneQueueComplete($event, dz);"
              (maxfilesreached)="onDropZoneMaxfilesReached($event)"
              (maxfilesexceeded)="onDropZoneMaxfilesExceeded"></dropzone>
</div>

<div class="row">
    <div class="col-md-12">
        <FilesList></FilesList>
    </div>
</div>

The Dropzone-component shows the dropzone. The FilesList shows the datatable. Part of the HTML:

<p-dataTable [hidden]="loading" [value]="files" selectionMode="single" (onRowSelect)="details($event)">

In my main ts-file I have:

@ViewChild(FilesListComponent)
public filesListComponent: FilesListComponent;

private reloadFileList() {
  this.filesListComponent.reload();
}

In my filelist ts I have

public files: File[];
public reload() {
    this.getFiles();
}
public getFiles() {
    this.fileService.getAll()
        .then(
        data => {
            this.files = data;
        });
}

getFiles is also called at page load. When I add console.log() statements I can see getFiles() is called and this.files is updated, but the table doesn't refresh.

5 comments

@twosouth 2017-10-26 18:25:49

UPDATE: I took a better look at the documentation for p-dataTable, particularly the section titled Change Detection. I removed the [immutable]=false attribute work-around in the p-dataTable tag and instead I'm now getting the table to refresh by returning something like this when I modify the underlying array:

return myOriginalArray.slice();

ORIGINAL: I was having trouble with getting p-datatable to update/refresh when I removed an item from the underlying array used to populate the table. No clue as to why, but adding the following attribute to the p-datatable tag fixed things for me:

[immutable]=false

I'm using PrimeNG ^4.1.3

@karthiks3000 2017-07-06 20:40:36

For anyone still looking for the new syntax of adding records to an array that is bound to a primeng table

this.arrayRecords= [...this.arrayRecords, newObject];

@Jeremy Thille 2017-07-28 08:08:09

Thank you! But it still bugs me that the way the records are altered decides of whether PrimeNG's table updates or not... If the element is pushed, the table doesn't update, and if the element is inserted using the spread operator, it does... Just why?

@karthiks3000 2017-08-04 17:38:05

I agree, I had to change all my code when I upgraded from angular 2 to angular 4 and this approach just doesn't seem right.

@HammerNL 2017-12-08 12:11:30

@JeremyThille The difference is caused by Angular's shallow change detection. If you use myArray.push(elem) the pointer to the array is not changed and Angular does not notice the change. By using myArray = [...myArray, elem] you instantiate a new array, so the pointer gets updated, and Angular will notice the change. Even though the spread operator solution is a bit less performant than push(), having Angular only do shallow change detection is a LOT more performant than deep change detection.

@Jeremy Thille 2017-12-08 12:53:42

@HammerNL oh wow, that's subtle. Thanks for the explanation.

@rbj325 2017-03-11 03:49:07

Update: PrimeNG recently removed the DoCheck interface which was automatically detecting changes, see: https://www.primefaces.org/primeng-4-0-0-rc4-released/

The answer is to use the spread operator( [...arr] - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator ) to add items to your array instead of .push().


Original Answer: I had a similar issue which I solved using a slightly different approach. If you are using the same service to upload and retrieve your files you can use RxJS instead of listening to events across components.

On my services I want to reload across the app when I make a POST or PUT I use:

  private _shouldUpdateSource = new BehaviorSubject<boolean>(false);
  shouldUpdateObservable = this._shouldUpdateSource.asObservable();

In your POST and/or PUT methods

this.http.post(..).map( res => {this._shouldUpdateSource.next(true);});

Which allows you to subscribe to the fileService.shouldUpdateObservable in your components:

 this.shouldUpdateSub = this.fileService.shouldUpdateObservable
  .subscribe((shouldUpdate: boolean) => {
    if (shouldUpdate) {
      this.updateFiles();
    }
  });

This seems to be the best way to handle communication about a service between components I've seen/used.

-Edit- Here is the same concept in the official documentation:
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service

-Edit 2- I ran into this issue again after updating to 4.0.0. FWIW, I ended up removing the PrimeNG Datatable, instead using a manual *ngFor and it worked fine. It seems that the PrimeNg documentation( https://www.primefaces.org/primeng/#/datatable ) tells you to:

"For example, use slice instead of splice when removing an item or use spread operator instead of push method when adding an item."

I'm not sure why they ask you to do this because it is contrary to what the official Angular documentation tells you to do but I believe it has something to do with why the [value] binding not working as you would expect.

Personally, I am moving away from PrimeNg in favor of the Covalent data table which has an explicit refresh() function: https://teradata.github.io/covalent/#/components/data-table

@Paul Meems 2017-03-12 09:57:36

Thanks rbh325 for your reply. It seems I can listen to the shouldUpdate event, but still no refreshing of my table. In fact this event is called so many times it freezes my page. I tried to create a plunker page: plnkr.co/edit/PdlI6Ay9KIETTcI1Y6VJ but I'm also new to plunker and can't get it to work but hopefully you can see what I'm doing wrong.

@rbj325 2017-03-12 21:09:23

_shouldUpdateSource should be in file-service.ts. I don't see that file in the plunkr. The whole issue you are experience is cross-component communication. The idea here is to move it to a service and out of the component. You can't mock your service call in a component, it isn't handled the same way.

@Dany Y 2017-05-27 14:34:57

The answer is to use the spread operator( [..arr] ) to add items to your array instead of .push(). what do you mean by this ? what is the syntax to use?

@Hemant Kumar 2017-05-30 10:52:50

thanks you so much.... its work for me.

@rbj325 2017-05-31 20:14:10

Added spread operator link.

@blazehub 2017-05-16 10:03:45

We can mark the view for check and call detechchange.

@ViewChild('searchDt') searchTable: DataTable;


self.dealService.getAccounts(self.searchParams).subscribe((response) => {       
   Deal.setAvailableAccount(response.map((current) => {
     return {
        "cifNumber": current['cif'],
        "ucic": current['ucic'],
        "accountNomenclature": current['customerName'],
     }
   }));

   **self.searchTable.changeDetector.markForCheck();
   self.searchTable.changeDetector.detectChanges();**
});

@Ben Richards 2017-03-09 17:56:27

I suspect this has to do with how your child component is handling changes. You should implement the onChange event and set the files that way. Here is an example:

```

export class FilesListComponent implements OnChanges {
    @Input() files: File[];

    ngOnInit() {
    }

    // Subscribe to the change event and update the model
    ngOnChanges(changes: {[propName: string]: SimpleChange}) {
        let key = 'files';
        this.files = changes[key].currentValue;
    }
}

```

@Paul Meems 2017-03-10 21:06:19

Thanks Boyan for your reply. I can't get it to work. Somehow ngOnChanges is never called. I updated my import: import { Component, OnInit, OnDestroy, OnChanges, SimpleChange, Input } from "@angular/core";

@Ben Richards 2017-03-10 21:22:00

Paul, you trigger the change detection by simply assigning the files result array to the input "files."

@Paul Meems 2017-03-10 21:52:06

You mean what I do in my getFiles()? I assign this.files = data; or do I need to assign it somewhere else?

@Ben Richards 2017-03-14 01:11:35

Create an input on the FilesList component (let's say "Data") and set it's data with filesListComponent,Data = data;

Related Questions

Sponsored Content

21 Answered Questions

[SOLVED] LINQ query on a DataTable

0 Answered Questions

PrimeNG - DataTable sorting

  • 2017-11-27 13:33:07
  • mathieu lavergne
  • 198 View
  • 1 Score
  • 0 Answer
  • Tags:   datatable primeng

0 Answered Questions

primeNg remove selected row on refresh dataTable

2 Answered Questions

[SOLVED] Angular2 adding PrimeNG to my solution tag not defined

1 Answered Questions

[SOLVED] How to use template in PrimeNG datatable

1 Answered Questions

[SOLVED] Angular2 - PrimeNG dataTable rowexpansion doesn't expand

1 Answered Questions

PrimeNg DataTable click event

1 Answered Questions

0 Answered Questions

PrimeNG - DataTable with individual column selection

1 Answered Questions

[SOLVED] angular 2 error : zone.js:484 Unhandled Promise rejection: Template parse errors

  • 2016-09-12 12:27:06
  • S_developer
  • 2016 View
  • 1 Score
  • 1 Answer
  • Tags:   angular primeng

Sponsored Content