user11680003
user11680003

Reputation:

confused with ngOnInit() and ngAfterContentInit()

I'm new to Angular, sorry if my questions sounds dumb. I always confused with ngOnInit() and ngAfterContentInit() lifecycle hooks. On the official docs, it says:

ngOnInit() : Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

ngAfterContentInit(): Respond after Angular projects external content into the component's view / the view that a directive is in.

My questions are:

Q1-For ngOnInit(), what does Initialize the directive/component after Angular first displays the data-bound properties mean? Does "Initialize " means create an instance of directive/component?

Q2-For ngAfterContentInit(), what's component's view means? does the view mean the associated template html in the component's templateUrl?

Upvotes: 3

Views: 1664

Answers (2)

Ethan Vu
Ethan Vu

Reputation: 2987

Q1: No, the creation of a class instance is the method constructor which happened before ngOnInit(), a component is a directive with a template data-bound properties, view nodes etc.. and ngOnInit() is called after data-bound properties is ready, and as you may known, ngAfterViewInit() is called after view ready.

Q2: I have one example for what the "content" mean:

You define a component selector inside app.component.html with a text inside :

<custom-component>
   Some random text
</custom-component>

Now inside custom-component.component.hml you can display the text "Some random text" using <ng-content></ng-content> which act as a placeholder for the text you passed down

<ng-content></ng-content>

ngAfterContentInit() simply mean the passing of "Some random text" into custom-component.component.hml view is completed.

Upvotes: 2

Patricio Vargas
Patricio Vargas

Reputation: 5522

A1) First you need to know what data-bound properties is. This answer question should help you:

What is data-bound properties?

What creates first is the constructor() The constructor comes before the ngOnInit()

https://angular.io/guide/lifecycle-hooks

A2) Yes, the view is either the xxx.component.html or the template inside of the component.ts file

https://dev.to/devpato/displaying-data-in-angular-unofficial-docs-4nd4

What is the difference between ngAfterContentInit and ngAfterViewInit?

Upvotes: 0

Related Questions