typescript - Angular 2 (TypeScript) 中的 *ngIf 问题

标签 typescript angular

我正在使用 Angular 2 beta (TypeScript)。我遇到了一个奇怪的问题。我尝试了 Chrome、Firefox、Opera,结果都一样。

当我点击“切换”按钮时,它可以成功显示/隐藏文本“Hello World!”。

当我使用套接字从另一个浏览器发送命令时, bool 值“show”成功更改了背景,但是,文本没有显示/隐藏,看起来页面没有刷新。

import {Component, View} from 'angular2/core';
import {bootstrap} from 'angular2/bootstrap';
import {NgIf} from 'angular2/common';

@Component({
    selector: 'app'
})
@View({
    directives: [NgIf],
    template: `
      <button (click)="clicked()">Toggle</button>
      <div>
        <div *ngIf="show">
          <h2>Hello World!</h2>
        </div>
      </div>
    `
})
class App {
    show: boolean = true;

    constructor() {
        Socket.on {
            If (getMessage) {
                this.show = !this.show;
            }
        }
    }

    clicked() {
        this.show = !this.show;
    }
}

bootstrap(App);

最佳答案

我认为这是与区域相关的问题。后者负责通知 Angular 它需要处理更新。

这个问题可以给你一些提示:View is not updated on change in Angular2 .

你可以尝试这样的事情:

export class App {
  constructor(ngZone:NgZone) {
    this.ngZone = ngZone;
    Socket.on {
      this.ngZone.run(() =>
        If (getMessage) {
            this.show = !this.show;
        }
      });
    }
  }

  }

这个问题也可能与您的问题有关:Angular2 child property change not firing update on bound property .

希望对你有帮助, 蒂埃里

关于typescript - Angular 2 (TypeScript) 中的 *ngIf 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875066/

相关文章:

javascript - 如何从请求返回响应(post | get)?

javascript - 从 csv 文件转换为按列名称选择的特定列的数组

Angular HttpInterceptor - 处理异步响应

typescript - 如何使用 get 方法访问 Typescript 中对象的字段?

angular - 类型 'select2' 上不存在属性 'JQuery<HTMLElement>'

css - 使用内联 CSS 设计组件样式 - Ionic2、AngularJS

angular - ionic 4/5 使用 ngx-translate 自动添加到 i18n 中的字幕文件

javascript - 如何在 Ionic 上使用 Highcharts?

javascript - 通过将旧的 AngularJS 迁移到 TypeScript,在 require.js 上忽略导入

javascript - Angular 6 - 日期管道