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?
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 aFormControl
. thus it works.
we can always create a control,
new FormControl({}, inputValidatorFn())
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.