2

全局事件(window.onresize)没有改变局部变量的值。

export class TestComponent implements OnInit {
    a: number = 0;
    b: number = 0;
    ngOnInit() {
        window.onresize = () => {
            this.a = 10;
            this.b = 10;
        };
    }
}

在此处输入图像描述

4

3 回答 3

1

使用主机绑定绑定到全局事件(这在 API 文档中提到,在 DirectiveMetadata 页面的深处):

@Component({
  selector: 'my-app',
  template: `<p>Resize window and look at console log.
    <p>{{a}} {{b}}`
})
export class AppComponent {
  @HostListener('window:resize') onResize() {
    this.a++;
    this.b++;
    console.log(this.a, this.b, event)
  }
}

plunker

您的原始代码不起作用,因为您将onresize处理程序(Angular 最初是猴子修补的)猴子修补到您自己的函数中。因此,Angular 不再有办法在事件处理程序完成后运行更改检测。使用主机绑定将 Angular 猴子补丁保持在适当的位置,因此它不会禁用更改检测,因此您的视图将在调整大小事件触发后更新。

于 2016-03-21T15:39:44.370 回答
0

我刚刚通过强制更新代码在 Angular Zone 中运行解决了类似的问题。我遵循的文档位于https://angular.io/docs/js/latest/api/core/index/DirectiveMetadata-class.html(截至今天 10/8/16)。

像这样的东西应该工作:

import {Component, OnInit, NgZone} from '@angular/core';

constructor(private _ngZone: NgZone) {
}

ngOnInit() {
    window.onresize = () => {
        this._ngZone.run(() => {
            this.a = 10;
            this.b = 10;
        }
    };
}

这比Mark Rajcok在这个问题中的回答要简单,但是 NG2 仍然是一个移动的目标,所以毫无疑问我所写的是已经做出的改进之一(例如,指向 DirectiveMetadata 的链接不再存在)。

于 2016-08-10T04:02:05.993 回答
0

没有改变局部变量的值

从您的屏幕截图中我可以看到,this.b = 10它确实改变了变量值。

在此处输入图像描述

在图片中你也看到了a: number = 0。这只是a自上一个断点以来的值。可以看到this.a也是10

于 2016-03-21T04:55:11.970 回答