angular – ng如果没有检测到var变化

前端之家收集整理的这篇文章主要介绍了angular – ng如果没有检测到var变化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用greensock动画库来动画一些组件(正如您所期望的那样).当我更新onComplete函数中绑定到* 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;
      }
    }
  };
}

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

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

@H_403_20@ 请参阅此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.

选项1:使用ngZone.run通知angular再次渲染视图.

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

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

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

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

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

原文链接:https://www.f2er.com/angularjs/143689.html

猜你在找的Angularjs相关文章