Scipion
Scipion

Reputation: 11888

Angular2 Notifying the template of a change

Here is my code :

@Component({
    selector: "foo",
    template: `
      <span>Init : {{o.init}}</span>
      <span>Loaded data : {{o.loadedData}}</span>
    `,
    providers: [
        Services
    ]
})
export class FooComponent implements OnInit{
   constructor (private _services: Services) {}

   o: Object
   ngOnInit() {
      o = {"init": "foo"}
      this.services.randomCall()
          .subscribe(
              res => this.o["loadedData"] = res["loadedData"]  
          )
   }
}

So o.loadedData doesn't appear everytime due to a race condition between my randomCall() and the template rendering. What I would like would be to notify angular after having assigned o["loadedData"] = res["loadedData"]. In angular1, I would have done a call to the scope's digest() function.

How can I do something similar in angular2 ?

Thanks !

Edit: I added back this, it was a typo.

Upvotes: 1

Views: 1505

Answers (2)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

Normally this is done by Angulars change detection which gets notified by its zone that change detection should happen. When code that somehow runs outside Angulars zone modifies your model, then you can invoke change detection manually like

export class FooComponent implements OnInit{
   constructor (private _services: Services, private cdRef:ChangeDetectorRef) {}

   o: Object
   ngOnInit() {
      o = {"init": "foo"}
      this.services.randomCall()
          .subscribe(
              res => {
                  o["loadedData"] = res["loadedData"];
                  this.cdRef.detectChanges();
              });
          )
   }
}

Because of the missing this as mentioned by Thierry, manual change detection won't help you in this case anyway.

For more options how to invoke change detection see Triggering Angular2 change detection manually

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202176

I would use the this keyword:

o: Object
ngOnInit() {
  this.o = {"init": "foo"}; // <-----

  this.services.randomCall()
      .subscribe(
          res => {
            this.o["loadedData"] = res["loadedData"]; // <-----
          }
      );
 }

Edit

You could force Angular2 to detect changes using the ChangeDetectorRef class, this way:

constructor(private cdr:ChangeDetectorRef) {
}

o: Object
ngOnInit() {
  this.o = {"init": "foo"};

  this.services.randomCall()
      .subscribe(
          res => {
            this.o["loadedData"] = res["loadedData"];
            this.cdr.detectChanges(); // <-----
          }
      );
 }

Upvotes: 4

Related Questions