I am having an issue with change detection in a dynamically added component in Angular.
I have added a link to a complete Plunker below.
The component has two properties (grid and message), with setters and getters for both properties.
The grid property is based on a "type" interface IGrid, and message is a string. Both grid and message are added to the component instance when the component is dynamically created and added to the parent component.
Setters for both grid and message call a function called consolelog.
Based on changes to their respective inputs, change detection for both grid and message seem to be working.
The issue i am having is that the consolelog function is being correctly called in the message setter, however the consolelog function is not being called correctly in the grid setter.
Template:
<div>
<div><b>grid.pinnedColumnHeaders</b></div>
input:
<input type="checkbox"
name="grid.pinnedColumnHeaders"
[(ngModel)]="grid.pinnedColumnHeaders">
</div>
<div>
value: {{ grid.pinnedColumnHeaders || '[blank]' }}
</div>
<hr>
<div>
<div><b>message:</b></div>
input: <input type="text" name="message"
[(ngModel)]="message">
</div>
<div>
value: {{ message || '[blank]' }}
</div>
Component:
@Component({
selector: 'app-change-detection-onpush',
template: `...`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChangeDetectionOnPushComponent implements IPage {
private _message: string;
private _grid: IGrid;
ngAfterViewInit() {
}
constructor(private cdRef: ChangeDetectorRef) { }
set grid(val: string) {
this.cdRef.markForCheck();
this.logconsole();
this._grid = val;
}
get grid() {
return this._grid;
}
set message(val: string) {
this.cdRef.markForCheck();
this.logconsole();
this._message = val;
}
get message() {
return this._message;
}
logconsole(){
console.log('test');
}
}
Complete Plunker: https://next.plnkr.co/edit/t1xK698tsJDnzS5E?open=lib%2Fapp.ts&deferRun=1
[(ngModel)]you are pointing to a property of agridobject, so when it changes - setter is not being called, because the object(link) isn't changing, so setter only calls when when the whole new object being passed through@Input. If you need to track changes ofcheckboxadd(change)="handleCheckboxChange($event)"to your html and declare same method in your component.