正如标题所述,我试图了解如何在Angulars更高版本中正确使用keyValueDiffer。问题不在于它本身的功能,但是当我创建它时,它表示由于对ChangeDetectorRef的压缩而对create()进行了描述。
this.diff = this.keyValueDiffer.find(obj).create(null);
现在怎么用?
在Angular 4.1.3和4.3.3
上尝试过答案 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
请注意,使用IterableDiffers
和IterableDiffer
服务(而不是KeyValueDiffers
和KeyValueDiffer
)