The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
Angular lifecycle hooks handle a component as it is created, checked, rendered, and destroyed. Template event bindings handle browser actions such as clicks and key presses, while component outputs send custom events from a child to a parent. Router events track navigation; they are a separate stream.
How Angular component lifecycle works
A component moves from creation through change detection and rendering to destruction. The constructor is ordinary class construction; Angular lifecycle hooks run as Angular checks and updates the component tree. During that traversal, Angular visits each component once, so avoid changing state midway through it. See Angular’s component lifecycle guide.
Choose a hook by what needs to be ready
| Hook or callback | When it runs | Use it for | Watch out for |
|---|---|---|---|
ngOnChanges |
When an input changes; it runs before ngOnInit on the initial input setting. |
Responding to input values, including their initial values. | It can run repeatedly as inputs change. |
ngOnInit |
Once, after Angular initializes the component’s inputs and before its template is initialized. | One-time setup that depends on initial inputs. | It is not a response to later input changes. |
ngAfterContentInit, ngAfterViewInit |
Once the projected content or component view, respectively, has initialized. | Work that requires the corresponding content or view query results to be available. | Changing component state here can cause ExpressionChangedAfterItHasBeenCheckedError. |
ngDoCheck, ngAfterContentChecked, ngAfterViewChecked |
During repeated checking. | Specific cases that cannot be handled by simpler hooks. | They run frequently and can affect performance; avoid them without a clear need. |
afterNextRender, afterEveryRender |
After Angular finishes rendering all components to the DOM. | Work that must happen after rendering. | These are application-wide callbacks, must be registered in an injection context, and do not run during server-side rendering or build-time prerendering. |
ngOnDestroy |
Just before Angular destroys the component. | Cleanup before the component goes away. | Register cleanup for resources or work that outlive the component. |
Angular does not guarantee the relative order of a lifecycle hook between a component and directives on the same element. Avoid depending on an order you happen to observe.
Handle native browser events in a template
Put the event name in parentheses to attach a native listener. Call a component method directly when you do not need the event object; use $event when the handler needs it. Angular documents this syntax in its template event listeners guide.
#1 Best Overall
<button (click)="save()">Save</button>
<input (keyup)="onKey($event)">
<input (keyup.enter)="submit()">
<input (keyup.shift.enter)="submitWithShift()">
Key filters such as .enter and modifier combinations such as .shift.enter narrow which keyboard events invoke a handler. Supported modifiers include alt, control, meta, and shift. A .code suffix matches a physical key code rather than the character it produces, which can matter when keyboard layout or input language changes that character.
For global listeners, prefix the event with window:, document:, or body:. If a handler should suppress the browser’s default action, call event.preventDefault() explicitly.
Rank #2
Send a custom event from a child to its parent
Declare an output in the child, emit it when the relevant action occurs, and listen to it on the child element in the parent template. Angular’s current guide recommends output() for new projects; the decorator-based @Output() and EventEmitter API remains supported. See custom events with outputs.
import { Component, output } from '@angular/core';
@Component({ selector: 'expandable-panel', template: '<button (click)="close()">Close</button>' })
export class ExpandablePanel {
panelClosed = output<void>();
close() {
this.panelClosed.emit();
}
}
<expandable-panel (panelClosed)="savePanelState()" />
Outputs can carry a value when the parent needs data. The parent receives the emitted value as $event:
Rank #3
// In the child:
selectionChanged = output<string>();
this.selectionChanged.emit('compact');
// In the parent template:
<item-picker (selectionChanged)="setLayout($event)" />
Output names are case-sensitive. Prefer camelCase names that do not collide with native DOM events. Custom Angular outputs do not bubble through the DOM, so an intermediate component must explicitly re-emit an event if it should pass the event onward. For programmatic subscriptions, the subscription has an unsubscribe() method; Angular automatically cleans up output subscriptions when it destroys a component that has subscribers.
Router events track navigation, not component or DOM events
If “lifecycle” means a route change, subscribe to Router.events. It emits navigation phases and outcomes, including NavigationStart, route recognition, guard and resolver events, NavigationEnd, NavigationCancel, and NavigationError. Check the event type and respond to the phase or outcome you need. These are distinct from component hooks and template listeners. See Angular’s routing lifecycle and events guide.
Rank #4
Quick decision guide
- Need one-time setup based on initial inputs? Use
ngOnInit. - Need to react whenever an input changes? Use
ngOnChanges. - Need initialized projected content or view query results? Choose the corresponding content or view initialization hook.
- Need DOM work after Angular renders? Consider
afterNextRenderorafterEveryRender, with their server-rendering and injection-context constraints in mind. - Need to release resources before a component is removed? Use
ngOnDestroyorDestroyRef. - Need to respond to a click or key press? Bind the native event in the template.
- Need a child to notify its parent? Use a component output.
- Need to track route navigation? Listen to
Router.events.
Check the Angular version used by your project when applying API guidance; these links point to Angular’s current, unversioned documentation.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

