typebytes / angular-checklist

🔥 Curated list of common mistakes made when developing Angular applications
https://angular-checklist.dev
MIT License
316 stars 66 forks source link

put init logic in the ngOnInit lifecycle hook is incorrect #118

Open DmitryEfimenko opened 6 months ago

DmitryEfimenko commented 6 months ago

put init logic in the ngOnInit lifecycle hook is not the best practice.

Please have a look at this article on AngularInDepth

igornowosad commented 6 months ago

I think this practice should be called "Don't put component logic in the constructor" instead.

geromegrignon commented 6 months ago

component logic is perfectly fine in a constructor. ngOnInit has been promoted as the way-to-go but the only benefit is being able to deal with @Input.

Using a constructor to populate a form with the response of an API call based on a route param is perfectly fine.

However, as pinpointed by @DmitryEfimenko, this practice is not a 'best one'. I'll remove it.

igornowosad commented 6 months ago

@geromegrignon in my opinion it’s not a place for that, because constructor fires when Angular constructs component tree, so the DOM element of form could be not ready.

Or I’m missing something 🤔

geromegrignon commented 6 months ago

The DOM is initialized after ngOnInitis triggered: how would it help? Populating the variable/AbstractControl of a form is unrelated at updating the DOM for it.

geromegrignon commented 6 months ago

I'll remove this item: It will require a full rewrite, more related to: 'how to init logic in a component'.