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