Angular2: * ngFor is not updated when updating the array

I have an array of objects (let's call it arr). In one of my component inputs in a method, (change)I change one of these attributes of an object, but *ngFornothing changes in view ( ). I read that Angular2 change detection does not check the contents of arrays or objects, so I tried these:

this.arr = this.arr.slice();

and

this.arr = [...this.arr];

But the view does not change; it still shows the old attribute. In method (change)c, console.log()I got the correct array. Strange, but it works: this.arr = []; I also tried NgZoneand markForCheck().

+15
source share
6 answers

,

this.arr = Object.assign({}, NEW_VALUE);
+2

trackBy *ngFor, . 100% , () , . Angular , - trackBy:

*ngFor="let item of (itemList$ | async); trackBy: trackItem"

:

*ngFor="let item of itemList; trackBy: trackItem"

:

trackItem - :

public trackItem (index: number, item: Item) {
  return item.trackId;
}
+6
  • , changeDetection: cHangeDetectionStrategy.OnPush, , changeDetectorRef.markForCheck()
  • onChange .
+3

, markForCheck(), DetectionChanges ( , , markForCheck ). , :

ChangeDetectorRef :

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

ChangeDetectorRef :

constructor(
    private changeDetection: ChangeDetectorRef
  ) { }

:

this.changeDetection.detectChanges();
+2

, changDetection @component

    @Component({
      selector: 'app-page',
      templateUrl: './page.component.html',
      styleUrls: ['./page.component.scss'],
      changeDetection: ChangeDetectionStrategy.Default
    })

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';

Push Default

OnPush CheckOnce, , , , Default (CheckAlways). .

Default CheckAlways, .

+1

- , , , , , .

@ViewChild(MyComponent, { static: true }) private test: MyComponent ngfor. ( , )

I managed to fix this by adding an attribute #mycompto the tag of my component in html and changing the above value to@ViewChild('mycomp', { static: true }) private test: MyComponent

0
source

Source: https://habr.com/ru/post/1681968/


All Articles