0
0
Angularframework~5 mins

ngOnInit for initialization in Angular - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is ngOnInit in Angular?

ngOnInit is a lifecycle hook method in Angular components. It runs once after the component's data-bound properties are initialized. It is used to perform component initialization tasks.

Click to reveal answer
beginner
When is ngOnInit called in the component lifecycle?

ngOnInit is called shortly after the component is created and after Angular sets the input properties. It happens before the component is displayed.

Click to reveal answer
intermediate
Why should you use ngOnInit instead of the constructor for initialization?

The constructor is for simple setup like dependency injection. ngOnInit is better for initialization that needs Angular bindings or inputs to be ready.

Click to reveal answer
beginner
How do you implement ngOnInit in an Angular component?

Implement the OnInit interface and add the ngOnInit() method inside your component class. Angular calls this method automatically.

Click to reveal answer
intermediate
Can ngOnInit be async? How to handle async initialization?

Yes, ngOnInit can be async by marking it async. You can use await inside it to wait for data before continuing.

Click to reveal answer
What is the main purpose of ngOnInit in Angular?
ATo handle user events
BTo initialize component data after inputs are set
CTo define component styles
DTo create services
When is ngOnInit called during the component lifecycle?
AAfter input properties are set but before display
BAfter the component is displayed
CBefore the constructor
DOnly when the component is destroyed
Which interface must a component implement to use ngOnInit?
AOnInit
BAfterViewInit
COnDestroy
DDoCheck
Why is it better to put initialization code in ngOnInit rather than the constructor?
ABecause <code>ngOnInit</code> is optional
BBecause <code>ngOnInit</code> runs multiple times
CBecause constructors cannot access inputs
DBecause constructors are slower
Can ngOnInit be asynchronous to wait for data?
AOnly in AngularJS
BNo, it must be synchronous
COnly if you use Observables
DYes, by marking it <code>async</code> and using <code>await</code>
Explain what ngOnInit is and why it is important for Angular component initialization.
Think about when Angular sets input properties and when you want to run your setup code.
You got /4 concepts.
    Describe how to implement ngOnInit in a component and how to handle asynchronous initialization inside it.
    Remember the syntax and how async/await works in modern JavaScript/TypeScript.
    You got /4 concepts.