如何从类属性TypeScript监听值更改

如何从类属性TypeScript监听值更改

本文介绍了如何从类属性TypeScript监听值更改-Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在AngularJS中,我们可以使用$watch$digest ...来侦听变量更改,而新版本的Angular(5,6)不再可能.

In AngularJS, we can listen variable change using $watch, $digest... which is no longer possible with the new versions of Angular (5, 6).

在Angular中,此行为现已成为组件生命周期的一部分.

In Angular, this behaviour is now part of the component lifecycle.

我检查了官方文档和文章,尤其是对> Angular 5更改检测在可变对象上,以了解如何在 TypeScript类/ Angular

I checked on the official documention, articles and especially on Angular 5 change detection on mutable objects, to find out how to listen to a variable (class property) change in a TypeScript class / Angular

今天提出的是:

import { OnChanges, SimpleChanges, DoCheck } from '@angular/core';


@Component({
  selector: 'my-comp',
  templateUrl: 'my-comp.html',
  styleUrls: ['my-comp.css'],
  inputs:['input1', 'input2']
})
export class MyClass implements OnChanges, DoCheck, OnInit{

  //I can track changes for this properties
  @Input() input1:string;
  @Input() input2:string;

  //Properties what I want to track !
  myProperty_1: boolean
  myProperty_2: ['A', 'B', 'C'];
  myProperty_3: MysObject;

  constructor() { }

  ngOnInit() { }

  //Solution 1 - fired when Angular detects changes to the @Input properties
  ngOnChanges(changes: SimpleChanges) {
    //Action for change
  }

  //Solution 2 - Where Angular fails to detect the changes to the input property
  //the DoCheck allows us to implement our custom change detection
  ngDoCheck() {
    //Action for change
  }
}

这仅对@Input()属性有效!

如果我想跟踪组件自身属性(myProperty_1myProperty_2myProperty_3)的更改,则将无法使用.

If I want to track changes of my component's own properties (myProperty_1, myProperty_2 or myProperty_3), this will not work.

有人可以帮我解决这个问题吗?最好是与Angular 5兼容的解决方案

Can someone help me to solve this problematic ? Preferably a solution that is compatible with Angular 5

推荐答案

您仍然可以通过DoCheck生命钩子通过KeyValueDiffers检查组件的字段成员的值更改.

You can still check component's field members value change by KeyValueDiffers via DoCheck lifehook.

import { DoCheck, KeyValueDiffers, KeyValueDiffer } from '@angular/core';

differ: KeyValueDiffer<string, any>;
constructor(private differs: KeyValueDiffers) {
  this.differ = this.differs.find({}).create();
}

ngDoCheck() {
  const change = this.differ.diff(this);
  if (change) {
    change.forEachChangedItem(item => {
      console.log('item changed', item);
    });
  }
}

请参见 演示 .

see demo.

这篇关于如何从类属性TypeScript监听值更改-Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:06