gpt4 book ai didi

angular - ngIf 没有检测到 var 变化

转载 作者:太空狗 更新时间:2023-10-29 17:18:37 25 4
gpt4 key购买 nike

我正在使用greensock 动画库 为一些组件设置动画(如您所料)。我在 onComplete 函数中更新绑定(bind)到 *ngIf 的变量时遇到问题。出于某种原因,angular 没有检测到回调中变量的更新。


预期功能:

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对于以下...

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

您可以在控制台中看到回调成功触发并更新变量,但是绑定(bind)到 *ngIf 的元素不会更改直到您单击其中一个灰色图像第二次

我如何让它在 onComplete 回调中按预期更新?

最佳答案

请引用 Angular 2 文档:Lifecycle Hooks

根据文档,

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.

方案一:使用ngZone.run通知angular再次渲染view。

// import ngZone from @angular/core first.
this.ngZone.run(() => {
console.log("anim complete");
this.rightVisible = false;
});

选项2:使用ChangeDetector让angular重新渲染 View 。

import {ChangeDetector} from '@angular/core';

this.rightVisible = false;
this.cd.detectChanges();

引用这个plunker包含上层代码块。

关于angular - ngIf 没有检测到 var 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42755184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com