What is the component lifecycle? Describe the main hooks.
Model answer
Angular creates, updates and destroys components and lets you run code at key moments. The main hooks are: ngOnChanges (when an input changes), ngOnInit (once, after the first inputs are set, the usual place for setup), ngDoCheck (each change detection run), ngAfterViewInit (after the view and child views exist), and ngOnDestroy (just before the component is removed, to clean up).
There are also afterNextRender and afterRender functions for code that must run after the DOM is updated, which is useful for browser-only work.
Tips
- Say what you use ngOnDestroy for: subscriptions, timers, listeners.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- What are the parts of a component?
- What is data binding? Explain the four types.
- What is the difference between interpolation and property binding?
- How do you pass data from a parent component to a child component?
- How does a child component send data to its parent?
- What is the difference between the constructor and ngOnInit?