💻 Tech
You might have come across this error below:
ERROR RuntimeError: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Hello'. Current value: 'hi'. Expression location: _ParentComponent component. Find more at https://angular.dev/errors/NG0100
It happens because the unidirectional flow of the data is not followed. In Angular lifecycle, a change detection ensures that no inconsistency happens during the lifecycle. Parent component renders greetings
then initializes the child component, which sets parent’s greetings
to another value. This causes the error to happen because Angular doesn’t expect this to happen.
One way to fix this is to change how data are changed. In our example, the order of how values are rendered matter. In the parent component, if you switched the position of greetings
value interpolation and the app-child
component declaration in the parent template, the error will not appear. This is because greetings
was changed first in the child component before being used in rendering its value.
Parent component
<p>{{ greetings }}</p>
<app-child></app-child>
export class ParentComponent {
greetings = 'Hello';
}
Child component
export class ChildComponent implements OnInit {
private parentComponent = inject(ParentComponent);
ngOnInit(): void {
this.parentComponent.greetings = 'hi';
}
}
One way to fix this:
<app-child></app-child> <!-- now the first one to be rendered -->
<p>{{ greetings }}</p>