Angular 2 OnPush Change Detection for Dynamic Components

I have an Angular component that dynamically creates various other components within myself. It binds its properties to @Input child components using the OnChanges hook.

This binding works great when the default value is set to detect a change in a child component. Then new inputs are detected and the component template is updated.

However, this does not work when the change detection is OnPush, then the change is not detected. I believe that a change should be detected because a new immutable object, a string, is assigned to the property of the @Input component.

Here's the plunker to demonstrate: https://plnkr.co/edit/0wHQghtww2HXVbC27bC1

How can I bind the parent-to-dynamic-child property to work with ChangeDetectionStrategy.OnPush?

+6
source share
1 answer

As a possible workaround for the OnPush component, setter will be used along with cdRef.markForCheck() :

discovery change-onpush.component.ts

 @Component({ selector: 'app-change-detection-onpush', template: ` <div> ChangeDetectionStrategy.OnPush: {{ message || '[blank]' }} </div>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class ChangeDetectionOnPushComponent implements IMyComponent { private _message: string; constructor(private cdRef: ChangeDetectorRef) {} set message(val: string) { this.cdRef.markForCheck(); this._message = val; } get message() { return this._message; } } 

Modified Plunker

+4
source

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


All Articles