angular - ngIf 没有检测到 var 变化

标签 angular typescript

我正在使用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/

相关文章:

javascript - 如何在angularjs中声明一个函数

angular - 如何让子组件和父组件之间的 Angular 2 通信正常工作?

javascript - Angular2-moment,MongoDB UTC 时间

angular - 在 Angular/Typescript 中单击后动态绑定(bind)

typescript - 我们如何在 Nextjs 动态导入中输入forwardRef?

无法分配给引用或变量中的 Angular 产品生成错误

javascript - 允许 Angular 4 路由传递 URL 中的特殊字符

html - Angular 跨度

Typescript 从默认值推断泛型类型

node.js - 如何在 Dockerfile 中编译 typescript