LonsomeHell
LonsomeHell

Reputation: 593

Angular2 View not updating after variable change

I have this component ( and another one with the same problem). When the field value changes the view is not updated I even tried to force a change detection but it didn't work.

Angular-cli 1.0.0-beta.10
Angular 2.0.0-rc.4

Component.js

import {Component, OnInit, OnDestroy, ChangeDetectorRef} from '@angular/core';
import {Control} from '@angular/common';
import {WebsocketService} from './websocket.service';


@Component({
  moduleId: module.id,
  selector: 'chat',
  template: `<div *ngFor="let message of messages">
                     {{message.text}}
                   </div>
                   <input [(ngModel)]="message"  /><button (click)="sendMessage()">Send</button>`,
  providers: [WebsocketService]
})


export class DummyWebsocketComponent implements OnInit, OnDestroy {
  messages = [];
  connection;
  message;

  constructor(private chatService:WebsocketService, private changeDetector:ChangeDetectorRef) {
  }

  sendMessage() {
    this.chatService.sendMessage(this.message);
    this.message = '';
  }

  ngOnInit() {
    this.connection = this.chatService.getMessages().subscribe(message => {
        this.messages.push(message);
        console.info(this.messages);
        this.changeDetector.markForCheck();
      },
      error => console.error(error),
      () => this.changeDetector.markForCheck()
    );

  }

  ngOnDestroy() {
    this.connection.unsubscribe();
  }
}

The chatService.getMessages returns an Observable.

Upvotes: 0

Views: 870

Answers (1)

LonsomeHell
LonsomeHell

Reputation: 593

It turns out I have set changedetectionstrategy to onPush in the parent component. And the message don't have a text field rather a message one so even forcing an update won't have any effect. If anyone have a similar problem look for changedetectionstrategy of the parent components too.

Upvotes: 3

Related Questions