angular - 角度 8 在 onchanges 事件中修改了一个变量,但是当我想访问它时,我发现它没有改变
问题描述
我在 angular 中有一个应用程序,并且我有一个具有自定义属性“modeInsert”的组件,并且我在 ngOnChanges() 事件中检测到此属性的更改,如下所示:
import { Component, OnInit, Input, ViewChild, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-update-cv',
templateUrl: './update-cv.component.html',
styleUrls: ['./update-cv.component.css']
})
export class UpdateCVComponent implements OnInit ,OnChanges {
constructor() { }
mode:boolean;
ngOnInit() {
}
ngOnChanges(changeRecord: SimpleChanges): void {
if(typeof changeRecord.modeInsert !== 'undefined'){
this.mode=changeRecord.modeInsert.currentValue;
console.log("changeRecord._modeInsert :"+this.mode);
}
}
@Input() modeInsert: boolean;
@ViewChild('closebuttonUpdateCV',{static: false}) closebuttonUpdateCV;
onUpdateCV(cv){
console.log(" onUpdateCV mode ="+this.mode)
if(this.mode){
console.log(" mode = ajout")
}else {
console.log(" mode = modif")
}
this.closebuttonUpdateCV.nativeElement.click();
}
}
,这个变量在Onchanges Event中改变了它的值,但是当我试图达到它的值时,我发现它并没有改变,就像在方法onUpdateCV(cv)中一样。
解决方案
您将在 ngOnChanges 中获得当前和以前的值
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
let chng = changes[propName];
let cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue);
}
}