ng如果未检测到var变化 [英] ngIf not detecting var change
问题描述
我正在使用 greensock动画库为某些组件制作动画(正如您所期望的那样).我在更新绑定到*ngIf
的onComplete
函数中的变量时遇到问题.出于某种原因,角度未在回调中检测到对变量的更新.
预期功能:
I am using the greensock animation library to animate some components (as you would expect). I am experiencing an issue when I am updating a variable in the onComplete
function which is bound to a *ngIf
. For some reason, angular is not detecting the update to the variable in the callback.
Intended functionality:
1. click grey image.
2. pink image fades out
3. one of the grey images dissapears.
当前功能:
1. click grey image.
2. pink image fades out
3. (nothing happens)
4. click grey image - again.
5. one of the grey images dissapears.
对于以下内容,我有 plunkr ...
I have a plunkr for the following...
declare var TweenMax; // defined in index.html
@Component({
selector: 'my-app',
template: `
<img *ngIf="leftVisible" src="http://placehold.it/350x150" (click)="animate(-1)"/>
<img *ngIf="rightVisible" src="http://placehold.it/350x150" (click)="animate(1)"/>
<img #otherImage src="http://placehold.it/350x150/ff00ff/000000"/>
`,
})
export class App {
@ViewChild('otherImage') otherImageElement;
private leftVisible: boolean;
private rightVisible: boolean;
constructor() {
this.leftVisible = this.rightVisible = true;
}
private animate(_direction: number){
var tween = TweenMax.to(this.otherImageElement.nativeElement, 1, {
opacity: 0,
onComplete: () => {
console.log("anim complete");
this.rightVisible = false;
}
}
};
}
您可以在控制台中看到回调成功触发并更新了变量,但是绑定到*ngIf
的元素不会更改,直到您再次单击其中一张灰色图像.
You can see in the console that the callback fires successfully and updates the variable, however the element which is bound to the *ngIf
does not change until you click one of the grey images a second time.
如何在onComplete
回调中按预期进行更新?
How do I get this to update as intended in the onComplete
callback?
推荐答案
请参阅以下Angular 2文档:生命周期挂钩
please refer to this Angular 2 documentation: Lifecycle Hooks
根据文档
Angular的单向数据流规则禁止在视图组成后对其进行更新.组成组件的视图之后,这两个钩子都会触发.
Angular's unidirectional data flow rule forbids updates to the view after it has been composed. Both of these hooks fire after the component's view has been composed.
选项1 :使用ngZone.run
通知angular重新渲染视图.
Option1: use ngZone.run
to notify angular to render the view again.
// import ngZone from @angular/core first.
this.ngZone.run(() => {
console.log("anim complete");
this.rightVisible = false;
});
选项2 :使用ChangeDetector
允许angular重新渲染视图.
Option2: use ChangeDetector
to let angular to render the view again.
import {ChangeDetector} from '@angular/core';
this.rightVisible = false;
this.cd.detectChanges();
请参阅包含上部代码块的 plunker .
Refer this plunker that contains the upper code block.
这篇关于ng如果未检测到var变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!