Foxhunt
Foxhunt

Reputation: 901

Angular - Refreshing mat-table from array change

I have an app call watcher, composed of a component / service. I have a simple table which shows empty properly

    <table mat-table [dataSource]="this.getWatcherTable()" class="mat-elevation-z8">
  
        ... my columns and rows are described here

    </table>

The source is linked to my component file

export class WatcherComponent{

    constructor(public watcherService : WatcherService ) {}

    getWatcherTable(){
        return this.watcherService.watcherTable;
    }
}

Itself linked to the service file

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable.push({name:name, value:value});
    }
}

The update is trigger by another app and works well, a console log of the array have the update, but the array is still displayed empty

Upvotes: 0

Views: 651

Answers (1)

Dariusz Ostolski
Dariusz Ostolski

Reputation: 472

Every time you update an array you should create new one so Angular change detection will update automatically component. So instead:

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable.push({name:name, value:value});
    }
}

You should have:

export class WatcherService {
    watcherTable : Array<Watcher> = new Array();

    updateWatchers(name,value){
        this.watcherTable = this.watcherTable.concat([{name:name, value:value}]);
    }
}

Upvotes: 1

Related Questions