Trouble with *ngIf in Angular 2 (TypeScript)

后端 未结 2 1811

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 successfu

相关标签:
2条回答
  • 2021-01-04 09:45

    Seems the Socket code runs outside Angulars zone. Inject NgZone and use zone.run(...) so Angular to make Angular aware of necessary change detection.

    class App {
      show: boolean = true;
    
      constructor(zone: NgZone) {
        Socket.on {
            if (getMessage) {
                zone.run(() => { this.show = !this.show; });
            }
        }
      }
    
    
      clicked() {
        this.show = !this.show;
      }
    }
    
    0 讨论(0)
  • 2021-01-04 09:57

    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

    0 讨论(0)
提交回复
热议问题