Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using FormBuilder in the constructor a bad practice?

Angular doc here you can see below kind of implementation.i.e declare formBuilder and services inside the constructor(). I know use services inside the constructor() is a bad practice. i.e. we need to use ngOnInit() for that. But I also use constructor() for declaring formBuilder properties. Is that too bad practice? Do I need to use ngOnInit() for that too? Will page creation holds until formBuilder creation?

export class CartComponent {
  items;
  checkoutForm;

  constructor(
    private cartService: CartService,
    private formBuilder: FormBuilder,
  ) {
    this.items = this.cartService.getItems();

    this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
  }
}
like image 510
Sampath Avatar asked Oct 24 '25 12:10

Sampath


1 Answers

Short answer, yes, you should leave most of the initialisation logic within the ngOnInit lifecycle hook.

According to the angular docs for OnInit, it is used to

  • To perform complex initializations shortly after construction.
  • To set up the component after Angular sets the input properties.

Therefore, it will be cleaner to carry out logic such as fetching of data, and initialisation of your formbuilders on your ngOnInit lifeycle hook.

You should check out this post by Misko Hevery, who is the team lead for Angular, who has outlined a number of reasons to keep the constructor clean.

like image 57
wentjun Avatar answered Oct 27 '25 03:10

wentjun