ng如果没有检测到var变化

Zze*_*Zze 8 typescript angular

我正在使用greensock动画库来动画一些组件(正如您所期望的那样).当我更新onComplete绑定到a 的函数中的变量时,我遇到了一个问题*ngIf.出于某种原因,angular不会检测回调中变量的更新.


预期功能:

1. click grey image.
2. pink image fades out
3. one of the grey images dissapears.
Run Code Online (Sandbox Code Playgroud)

目前的功能:

1. click grey image.
2. pink image fades out
3. (nothing happens)
4. click grey image - again.
5. one of the grey images dissapears.
Run Code Online (Sandbox Code Playgroud)

我有一个以下的傻瓜 ......

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;
      }
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pen*_*gyy 10

请参阅此Angular 2文档:Lifecycle Hooks

根据文件,

Angular的单向数据流规则禁止在编写视图后对视图进行更新.组件的视图组成后,这两个钩子都会触发.

选项1:用于ngZone.run通知角度再次渲染视图.

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

Option2:用于ChangeDetector让angular再次渲染视图.

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

this.rightVisible = false;
this.cd.detectChanges();
Run Code Online (Sandbox Code Playgroud)

请参阅包含上部代码块的此plunker.