Should FormBuilder be utilized in the constructor or is it considered a poor practice?

section, you can find an example of implementation where declarations for formBuilder and services are done within the constructor(). While it is commonly known that using services inside the constructor() is not a recommended practice and should be done within ngOnInit(), there seems to be confusion regarding the declaration of formBuilder properties in the constructor(). Is this also considered bad practice? Should ngOnInit() be used for declaring formBuilder properties as well? Will the page creation be delayed until formBuilder properties are created? Below is a snippet of code showcasing this scenario:
export class CartComponent {
  items;
  checkoutForm;

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

    this.checkoutForm = this.formBuilder.group({
      name: '',
      address: ''
    });
  }
}

Answer №1

Yes, it is best practice to keep most of the initialization logic within the ngOnInit lifecycle hook.

The Angular documentation for OnInit states that this hook is used:

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

Therefore, tasks like data fetching and form builder setup should be handled in the ngOnInit hook for cleaner code implementation.

You may also want to read this insightful article by Misko Hevery, the team lead for Angular, which elaborates on the importance of keeping constructors clean.

Answer №2

Utilizing FormBuilder within the Constructor

Utilizing FormBuilder within the constructor is considered a best practice in Angular, as it aligns with the constructor injection pattern.

Deciding on Using FormBuilder in the Constructor

The decision of whether to set up the reactive form in the constructor or during the ngOnInit lifecycle hook is often based on personal preference. However, for the sake of clarity and organization, moving initialization logic to ngOnInit (or other methods) is advisable.

As per the timing of ngOnInit, it occurs:

[after] the default change detector checks the directive's data-bound properties for the first time, and prior to checking any of the view or content children. This method is triggered only once during the instantiation of the directive.

Therefore, initializing a form in ngOnInit will happen before the page view loads.


The official documentation for Angular on Reactive Forms showcases how to initialize a form:

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: ['', Validators.required],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
    aliases: this.fb.array([
      this.fb.control('')
    ])
  });

  get aliases() {
    return this.profileForm.get('aliases') as FormArray;
  }

  constructor(private fb: FormBuilder) { }
}

View the Angular Stackblitz Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Every item in my array is replaced by the most recently added element

Take a look at this code snippet on JSFiddle: https://jsfiddle.net/reko91/998woow6/ The issue I am facing with my project is that every time I add an element to an array, it ends up overwriting all the existing elements with the newly added one. To repli ...

Typescript is unable to comprehend that the initial item in an array of strings is considered to be a string

Here are the functions I am working with: const transitionGroup = ( propertyName: string, durationMultiple = 1, timingFunction = 'linear', delayMultiple = 0, ): string => { // ...more logic here return [propertyName, duration, tim ...

Various array outcomes are produced by identical JavaScript (SAP UI5) code

Utilizing cachebuster to identify the modified file in the application structure. Javascript code snippet: https://i.sstatic.net/CZGfW.png Ineffective Array result: https://i.sstatic.net/D6MdS.png Effective Array result: https://i.sstatic.net/pQCIh.p ...

Purging data when no input is detected in React.js

I need to figure out a reliable way to detect when my input field has been cleared so that I can clear the associated data. Currently, I am using the logic if (searchTerm.length === 0) to check for a cleared input. However, I have also experimented with i ...

What is the best way to spy on child components within an Angular application?

The Angular tutorials feature an example of a HeroesComponent with a child component named HeroesListComponent. Within the HeroesListComponent, there is a usage of the HeroesService to execute the getHeroes() function. In order to utilize the spyOn funct ...

What is the best way to simulate a service HTTP request using Jasmine in an Angular application?

Why is my spy not working as expected? I've set up a spy for the prescriptionService and am monitoring the fetchClientPrescriptions method, but when I try to verify if it has been called, I encounter an error. However, the spy for getClientPrescriptio ...

Issues encountered while accessing REST in Angular 6 due to Access-Control-Allow-Origin restrictions

I am currently facing an issue with loading data from a REST source into my Angular 6 app using http: HttpClient from '@angular/common/http'. When I try to call the app in the browser using ng serve --open, it seems like CORS is causing a problem ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

Submit an Ajax form to process data in PHP upon selecting a radio button

I am troubleshooting an issue with a form that is not submitting data to processor.php for processing and storing responses in a database. Ensuring that the form submission does not cause a page refresh is crucial, as there is an iframe below the form tha ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

Error in Next.js 11: Unable to loop over undefined property

Upon upgrading Next.js from version 10 to 11, I encountered an error while running npm run build: Module parse failed: Cannot read property 'forEach' of undefined File was processed with these loaders: * ./node_modules/next/dist/build/babel/loade ...

Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong? <script setup ...

What is the best way to incorporate items into Redux reducers?

Incorporating Redux with Next JS, I am faced with the challenge of adding an array of objects to it. Within my application, there exists a form containing multiple inputs, and in order to accommodate these inputs, I have structured a form consisting of 10 ...

There was an issue with Sails.js where it was unable to retrieve a recently created user using a date

One issue I encountered with Sails.js was using sails-disk as the database. When querying for a user with specific date parameters, such as: // Assuming the current date is end_date var end_date="2014-06-06T15:59:59.000Z" var start_date="2014-06-02T16:0 ...

Manipulating HTML attributes with Jquery's attr() method results in returning [object Object]

Despite reading numerous articles and questions, I have yet to find a solution. My PHP page is designed to update an easypiechart using AJAX with database values checked every X minutes. For demonstration purposes, I have set the update interval to 10 seco ...

Refresh the module.exports in a Mocha unit testing script

I am currently learning about nodejs and mocha, and I have developed a JavaScript program to display the files in a folder along with a unit test case using the mocha and chai framework. My goal here is to reset the object set in module.export before each ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

The function 'toBlob' on 'HTMLCanvasElement' cannot be executed in react-image-crop because tainted canvases are not allowed to be exported

Currently, I am utilizing the react-image-crop npm package for image cropping purposes. Everything works perfectly when I pass a local image as props to the module. However, an issue arises when I try to pass a URL of an image fetched from the backend - th ...