0
点赞
收藏
分享

微信扫一扫

善用Angular的ngOnChanges和ngDoCheck生命周期钩子函数实现Vue中类似watch的功能(监听数据变化)


ngOnChanges主要用于组件的@Input变量监听

app.component.html

<input type="text" [(ngModel)]=text>
<input type="text" [(ngModel)]=text2>

<app-change [text]="text" [text2]="text2"></app-change>

这里如果遇到ngModel绑定报错,

app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
text = "text";
text2 = "text2";
}

change/change.component.html

<h1>父组件修改了text为{{text}}</h1>
<h1>父组件修改了text2为{{text2}}</h1>

change/change.component.ts

import { Component, Input, OnInit, SimpleChanges } from '@angular/core';

@Component({
selector: 'app-change',
templateUrl: './change.component.html',
styleUrls: ['./change.component.css']
})
export class ChangeComponent implements OnInit {

@Input() text: any = '';
@Input() text2: any = '';

constructor() { }
ngOnInit(): void {
}

ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
console.log(changes);//这里会监听到每次修改@Input变量的值
}
}

实际效果

善用Angular的ngOnChanges和ngDoCheck生命周期钩子函数实现Vue中类似watch的功能(监听数据变化)_ngDoCheck

 ngDoCheck用于任何情况下的数据变化(由于监听频率太大,慎用!)

app.component.html

<input type="text" [(ngModel)]=text>
<input type="text" [(ngModel)]=text2>

 app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {

text = "text";
text2 = "text2";

old_text = '';//记录旧的数据
old_text2 = '';//记录旧的数据2

ngDoCheck() {

// 【text】如果是新的数据,触发行为
if (this.text !== this.old_text) {
console.log(`【text】新的数据:${this.text},旧的数据:${this.old_text}`);
}

// 【text2】如果是新的数据,触发行为
if (this.text2 !== this.old_text2) {
console.log(`【text2】新的数据:${this.text2},旧的数据:${this.old_text2}`);
}

// 记录旧数据----------------------------------------
this.old_text = this.text;
this.old_text2 = this.text2;

}
}

实际效果 

善用Angular的ngOnChanges和ngDoCheck生命周期钩子函数实现Vue中类似watch的功能(监听数据变化)_数据监听_02

 

举报

相关推荐

0 条评论