Why should I create an Angular2 reactive form in the constructor instead of ngOnInit?

As pointed out in other answers , the initial procedures of the Angular2 application should be launched in the ngOnInit () method, leaving the constructor specifically for dependency injection.

However, in the Reactive Forms Tutorial that I run, initializing the form is in the constructor:

export class HeroDetailComponent3 { heroForm: FormGroup; // <--- heroForm is of type FormGroup constructor(private fb: FormBuilder) { // <--- inject FormBuilder this.createForm(); } createForm() { this.heroForm = this.fb.group({ name: '', // <--- the FormControl called "name" }); } } 

Is there really a significant difference or is this just a minor issue?

+5
source share
2 answers

I believe, because the createForm method in the constructor will execute before ngOninit, and your form will be ready for use as soon as your component is rendered.

+1
source

Initializing formGroup in ngOnInit() not a bad practice, as it will be really necessary if you want your form to be initialized with values โ€‹โ€‹that depend (directly or indirectly) on your @Input() s component.

For instance:

 class SignInFormComponent { @Input() currentLogin: string; formGroup: FormGroup; constructor() { // this.currentLogin is not known yet here } ngOnInit(): void { this.formGroup = this._fb.group({ loginEmail: [this.currentLogin, Validators.email], loginPassword: [''], }); } } 
0
source

Source: https://habr.com/ru/post/1267099/


All Articles