angular 4.X.X keyValueDiffer - how to use it?

Viewed 3358

As the title states, I am trying to understand how to properly use the keyValueDiffer in Angulars later versions. The problem is not the functionality itselves, but when I'm creating it, it says that create() is depricated due to deprication of ChangeDetectorRef.

this.diff = this.keyValueDiffer.find(obj).create(null);

How should it nowdays be used?

Tried it on Angular 4.1.3 and 4.3.3

https://angular.io/api/core/KeyValueDiffer

1 Answers
import {
  Component,
  OnInit,
  DoCheck,
  KeyValueDiffers,
  KeyValueDiffer,
} from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit, DoCheck
{    
   private _objDiff: { [any: string]: KeyValueDiffer<string, any> };
   private _dataToWatch: { [any: string]: any };

   public constructor(
      private _keyValueDiffers: KeyValueDiffers)
   {
      this._objDiff = {};
   }

   public ngOnInit(): void
   {
      this._dataToWatch = // get the data from some where...
      this._keyValueDiffers.find(this._dataToWatch).create();
   }

   public ngDoCheck(): void
   {
      const changes = this._objDiff.diff(this._dataToWatch);
      if(changes)
      {
         changes.forEachChangedItem((change) =>
         {
            if (change.currentValue != change.previousValue)
            {
               console.log("Value was changed!");
            }
         });
      }
   }
}

For more info see:
1. https://angular.io/api/core/DoCheck
2. https://angular.io/api/core/KeyValueDiffer
3. https://angular.io/api/core/KeyValueDiffers

Please notice that an Array change detection is done in a different way using the IterableDiffers and the IterableDiffer services (instead of KeyValueDiffers and KeyValueDiffer)

Related