Generic SimpleChanges
ngOnChanges is an Angular lifecycle hook that is called when the input properties of a component or directive are changed.
It exposes a SimpleChanges object that contains the old and new values of the changed properties:
@Input() name!: string;@Input() description!: string;
ngOnChanges(changes: SimpleChanges): void { console.log(changes.name.previousValue); console.log(changes.name.currentValue);
console.log(changes.description.previousValue); console.log(changes.description.currentValue);}ngOnChanges is useful to react to changes in the input properties of a component or directive.
For example, you can use it to:
- update a form
- update a chart
Exercise
Context of the exercise
The app is made of two parts:
- a list of events
- a form to edit an event
By clicking on an event, the form is filled with the event details.
The form part is routed with an router-outlet, grabbing the event details from the URL.
By enabling the withComponentInputBinding()router feature in the app.config.tsfile, queryparams are bound to the component @Input() properties.
So whenever the URL changes, the form is updated with the new event details, using the ngOnChanges lifecycle hook.
interface SimpleChange<T> { currentValue: T; previousValue: T; firstChange: boolean;}interface SimpleChange<T> { currentValue: T; previousValue: T; firstChange: boolean;}Task
The application currently fails to renders: open the browser console and see the error.
Fix the typo in the property name and use a proper type upon SimpleChanges<T>.
- Installing dependencies
- Start the application