B
B
bitalikrr2019-08-07 14:19:00
JavaScript
bitalikrr, 2019-08-07 14:19:00

Angular (8) why is the template not updating?

I have a component, it has a sensors property: Array
There is a line in the template

<div class="pr-sensors-item" *ngFor="let item of sensors">

The problem is that when I try to set new elements of the array, the template is not updated
, and this only happens if I change the array from the callback function after the Http Request
, i.e.:
getSensors() {
this.sensors = [{}, {}] // так работет и шаблон рендерится
this.sensorsService
      .get(this.machineParentId)
      .subscribe((response) => {
            this.sensors = response.sensors // так не работает
            // or
            this.sensors.push(...response.sensors)
      });
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Pikat, 2019-08-07
@bitalikrr

Do you happen to have a component in it changeDetection: ChangeDetectionStrategy.OnPush?
Angular detects changes in inputs by reference when OnPush. When you create a new list with
this.sensors = [{}, {}], you refer to the new list, and when you change the value through this.sensors.pushthe object reference does not change.
So either use the spread operator

this.sensors = [...this.sesnsors, ...response.sensors]

Or manually tell Angular to check for change via this.changeDetector.markForCheck()
(changeDetector from constructor, private changeDetector: ChangeDetectorRef)

D
Dmitry Eremin, 2019-08-07
@EreminD

*ngFor="let item of sensors$ | async;"

sensors$ = this.sensorsService.get(this.machineParentId);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question