Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

As indicated in other responses, the initial routines of an Angular2 application should be launched in the ngOnInit() method, leaving the constructor specifically for dependency injection.

However, in the Reactive Forms tutorial that I'm following, the initialization of 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 it just a minor issue?

like image 962
Rodrigo Avatar asked Apr 24 '17 15:04

Rodrigo


1 Answers

Initializing the formGroup in ngOnInit() is not a bad practice, as it will actually be required if you want your form to be initialized with values that depend (directly or indirectly) from your component @Input()s.

For instance:

class SignInFormComponent {
  @Input() currentLogin: string;
  formGroup: FormGroup;

  constructor(private fb: FormBuilder) {
    // this.currentLogin is not known yet here
  }

  ngOnInit(): void {
    this.formGroup = this.fb.group({
      loginEmail: [this.currentLogin, Validators.email],
      loginPassword: [''],
    });
  }
}
like image 190
Javarome Avatar answered Jan 03 '23 09:01

Javarome