Reputation: 806
I have a parent component which holds a property called documents. This property is an Array and is used to pass the documents in the array to a child component.
But when I push a new document into my property documents, the view of the child component is not changing. Can someone tell what I am doing wrong here?
This is my the place in the parent component where the property documents gets a change:
// handle the data that comes back from the dialog
createDialog.afterClosed().subscribe(
data => {
if (data){
// persist vital signs
this.documentService.saveDocument(data.newDocument); // not implemented yet because it makes no sense with non functioning backend
this.documents.push(data.newDocument);
// update the existing document bucket the document belongs to
this.loincToDocumentsMap.get(data.loincCode)?.folderContent.push(data.newDocument);
}
}
);
And this is my child component:
@Component({
selector: 'document-list',
templateUrl: './document-list.component.html',
styleUrls: ['./document-list.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DocumentListComponent implements OnInit, OnChanges {
@Input() documents: DocumentReference[] = [];
....
}
And this is where I use the child component in the parent component:
<document-list *ngIf="showListUi" [documents]="documents"></document-list>
I would really appreciate some help because the same worked with other components and I cannot see any difference. Another child component that lives in the same parent component for example is being updated correctly.
Update-1:
After adding this, the change detection works. But why?
this.documents = this.documents.filter(document => {
return true;
})
Update-2: Thanks everyone, solutions are in the answers:)
Upvotes: 1
Views: 5901
Reputation: 898
The reason why your UI is not updating is the OnPush change detection. The OnPush changedetection triggers only the changedetection (hence the render) is when the pointer of the array changes but doesnt check the content of the array. So if you add one item into the array it doesnt change the point of the array.
To solve this there are several solutions
Upvotes: 1
Reputation: 1442
Angular change detection only checks object identity, not object content. Inserts or removals are therefore not detected.
Please read here: https://stackoverflow.com/a/43223700/5835354 and https://stackoverflow.com/a/42962723/5835354
Upvotes: 6