在AngularJS中,我们可以使用$watch$digest...这在Angular(5,6)的新版本中不再可能.

在Angular中,这种行为现在是组件生命周期的一部分.

我查看了官方文档、文章,尤其是Angular 5 change detection on mutable objects,以了解如何在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)的更改,这将不起作用.

有人能帮我解决这个问题吗?最好是与Angular 5相容的溶液

推荐答案

您仍然可以通过DoCheck lifehook判断组件的字段成员值更改KeyValueDiffers.

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

100.

Typescript相关问答推荐

"@ clerker/nextjs/server没有名为clerkMiddleware的导入成员'

如何将http上下文附加到angular中翻译模块发送的请求

界面中这种类型的界面界面中的多态性

如何防止TypeScript允许重新分配NTFS?

如果在TypeScript中一个原始的类方法是递归的,如何使用类decorator 模式?

使用Angular和API请求在CRUD操作后更新客户端数据的良好实践

TS不推断类型在条件判断后具有属性'

如何在函数参数中使用(或模仿)`success`的行为?

找不到带名称的管道''

我用相同的Redux—Toolkit查询同时呈现两个不同的组件,但使用不同的参数

material 表不渲染任何数据

在TypeScrip的数组中判断模式类型

TypeError:正文不可用-NextJS服务器操作POST

vue-tsc失败,错误引用项目可能无法禁用vue项目上的emit

使用条件类型的类型保护

在组件卸载时try 使用useEffect清除状态时发生冲突.react +打字

我不明白使用打字脚本在模板中展开参考

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

无法缩小深度嵌套对象props 的范围

在Typescript 中,是否有一种方法来定义一个类型,其中该类型是字符串子集的所有可能组合?