Last active
April 27, 2023 15:33
-
-
Save Bludwarf/1334767e0124f78141f42dfa60e530c8 to your computer and use it in GitHub Desktop.
Angular change detection with MatTableDataSource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ChangeDetectionStrategy, Component, DoCheck, KeyValueDiffer, KeyValueDiffers} from '@angular/core'; | |
import {MatTableDataSource} from '@angular/material'; | |
interface Data { | |
} | |
const DATA: Data[] = []; | |
/** | |
* Provoque un changement de données pour qu'Angular détecte que les données ont été modifiées même si la variable n'a pas été modifiée. | |
* @see Source : https://stackoverflow.com/a/49224747/1655155 | |
*/ | |
export function refreshMatTableDataSource<T>(dataSource?: MatTableDataSource<T>): void { | |
if (dataSource) { | |
// noinspection SillyAssignmentJS : pour déclencher une détection de changement Angular | |
dataSource.data = dataSource.data; // NOSONAR : voir ci-dessus | |
} | |
} | |
@Component({ | |
changeDetection: ChangeDetectionStrategy.OnPush, // Pour limiter la fréquence des détections | |
}) | |
export class ChangeDetection implements DoCheck { | |
dataSource: MatTableDataSource<Data>; | |
private readonly dataDiffer: KeyValueDiffer<string, any>; | |
/** Booléen pour ignorer la première détection de changement, qui ne devrait pas être déclenchée */ | |
private firstChangesDetected = false; | |
constructor( | |
differs: KeyValueDiffers, | |
) { | |
this.dataSource = new MatTableDataSource<Data>(DATA); | |
this.dataDiffer = differs.find(this.dataSource.data).create(); | |
} | |
ngDoCheck(): void { | |
if (this.dataDiffer) { | |
const dataChanges = this.dataDiffer.diff(this.dataSource.data); | |
if (dataChanges) { | |
if (this.firstChangesDetected) { | |
refreshMatTableDataSource(this.dataSource); | |
} | |
this.firstChangesDetected = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment