Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with *ngIf in Angular 2 (TypeScript)

I am using Angular 2 beta (TypeScript). I met a weird problem. I tried Chrome, Firefox, Opera, all same results.

When I click the "Toggle" button, it can successfully show/hide the text "Hello World!".

When I send the command from another browser using socket, the boolean "show" changes successfully background, however, the text does not show/hide, which looks like the page does not refresh.

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);
like image 934
Hongbo Miao Avatar asked Jan 19 '16 11:01

Hongbo Miao


Video Answer


1 Answers

I think that it's a problem related to Zone. The latter is responsible to notify Angular that it needs to handle an update.

This question could give you some hints: View is not updated on change in Angular2.

You could try something like that:

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

  }

This question could be also related to your problem: Angular2 child property change not firing update on bound property.

Hope it helps you, Thierry

like image 73
Thierry Templier Avatar answered Oct 23 '22 03:10

Thierry Templier