Great insights provided. In my experience, utilizing ChangeDetectorRef and AfterViewInit in Angular can lead to additional rendering cycles. This can result in extra calls for view rendering, especially if the HTML code is not carefully designed or if multiple function calls in the TypeScript code depend on refresh.
To address this issue, I have found a simple and effective solution that bypasses these challenges. By using a zero-delay Promise to update values, I can separate the value update process into the next processing cycle, avoiding the common error message "Expression has changed after it was checked."
The key is a public function that applies a zero delay Promise to pass values:
export async function delayValue(v: any, timeOutMs: number = 0): Promise<any> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(v);
}, timeOutMs);
});
}
To implement this solution, simply use the function in one line of code:
this.myClassValue = await delayValue(newValue);
The negligible delay is due to the zero value set for timeOutMs.
This method can be particularly helpful in scenarios where you want to handle new values without encountering errors:
myObservable$.subscribe(newValue = {
...
this.handleSubscribedValues(newValue);
...
});
private handleSubscribedValues(newValue) {
this.myClassValue = newValue;
}
private async handleSubscribedValues(newValue) {
this.myClassValue = await delayValue(newValue);
}
Additionally, the delayValue() function can be customized with a delay/timeout value if needed, such as creating a brief pause for a user action.
I hope this strategy proves beneficial to those facing similar challenges.