Is there any difference between initializing a variable (like formGroup) inside the class directly or inside the constructor of class?

Viewed 283

I just wondering what is the difference between initializing formGroup inside the class or inside the constructor.

  1. Creating them when we are declaring them like this:

    form: FormGroup = this.formBuilder.group({})
    
  2. Declare its variable and then create them in constructor of class

    form: FormGroup;
    
    constructor(private formBuilder: FormBuilder) {
        this.form = this.formBuilder.group({})
    }
    

Are there any differences between these two approaches and what are the pros and cons of these two approaches?

1 Answers

What you showed is the same approach (inlined initialization will be moved to the constructor by the compiler).

Using the FormBuilder in itself is a short form though.

form: FormGroup = new FormGroup({
  c1: new FormControl('')
});

==

form: FormGroup = this.fb.group({
  c1: ['']
});
Related