angular 4.X.X keyValueDiffer - 如何使用它?

时间:2017-08-08 09:19:12

标签: angular deprecated

正如标题所述,我试图了解如何在Angulars更高版本中正确使用keyValueDiffer。问题不在于它本身的功能,但是当我创建它时,它表示由于对ChangeDetectorRef的压缩而对create()进行了描述。

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

现在怎么用?

在Angular 4.1.3和4.3.3

上尝试过

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

1 个答案:

答案 0 :(得分:0)

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!");
            }
         });
      }
   }
}

有关详细信息,请参阅:
1. https://angular.io/api/core/DoCheck
2. https://angular.io/api/core/KeyValueDiffer
3. https://angular.io/api/core/KeyValueDiffers

请注意,使用IterableDiffersIterableDiffer服务(而不是KeyValueDiffersKeyValueDiffer

以不同的方式完成阵列更改检测