-1

What is the difference between below methods:

input: new FormControl({}, inputValidatorFn())

input: [{}, inputValidatorFn()]

input: formBuilder.control({}, inputValidatorFn())

It seams to behave the same.

Or there is no difference at all?

Example

Adam Michalski
  • 1,619
  • 14
  • 32

2 Answers2

3

There is no difference at all.

Initializing a form control using FormBuilder uses the Factory Design Pattern, which is a better way of coding.

The angular site explains,

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl, FormGroup, or FormArray. It reduces the amount of boilerplate needed to build complex forms.

Dulanjaya Tennekoon
  • 1,727
  • 1
  • 12
  • 25
1

I will be a bit brief to answer this one.

so your code to build the form,

fb.group({
      newFormControl: new FormControl({}, inputValidatorFn()),

      arrayNotation: [{}, inputValidatorFn()],

      input: fb.control({}, inputValidatorFn()),
    })

here you are using fb.group() method to build a group of controls. If you see FormBuilder class declaration you will see it has multiple methods group(), control() and array()

lets see the definition of group method,

group(): it takes two parameter (controlsConfig and options) and return a FormGroup.

/**
 * Construct a new `FormGroup` instance.

 * @param controlsConfig : A collection of child controls. 
The key for each child is the name, under which it is registered.

 * @param options : Configuration options object for the `FormGroup`. 
With the help of this we can set validators, asyncValidators for that `FormGroup`.
*/


group(controlsConfig: {
    [key: string]: any;
}, options?: AbstractControlOptions | {
    [key: string]: any;
} | null): FormGroup;

you can build a control in two ways.

controlsConfig is an object of any type and we pass a collection of child controls.

fb.group() function understands that [{}, inputValidatorFn()] is a FormControl. thus it works.

we can always create a control,

  1. with FormControl - new FormControl({}, inputValidatorFn())
  2. with FormBuilder service - fb.control({}, inputValidatorFn())

They all return a FormControl that we need, so, there is no difference here.

A line from Angular documentation may be helpful.

Creating form control instances manually can become repetitive when dealing with multiple forms. The FormBuilder service provides convenient methods for generating controls.

so, for larger form we use array init form like yours [{}, inputValidatorFn()] of FormBuilder service.

Sadid Khan
  • 1,361
  • 14
  • 30