0

I created a form by calling a function from the constructor

constructor(private userManagementService: UserManagementService, private fb:FormBuilder) {
    this.createForm();
  }

  createForm(){
    this.signupForm = this.fb.group({
      firstName:['',Validators.required], 
      lastName:['',Validators.required],
      email:['',Validators.required],
      password:['',Validators.required]
    });
  }

I suppose I could also create the form in ngOnInit

constructor(private fb:FormBuilder) {

  }


ngOnInit{

    this.signupForm = this.fb.group({
      firstName:['',Validators.required], 
      lastName:['',Validators.required],
      email:['',Validators.required],
      password:['',Validators.required]
    });
  }

}

What is the difference between the two approaches? Is one better than the other?

Manu Chadha
  • 15,555
  • 19
  • 91
  • 184
  • Please go through this link: https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit – nithalqb Feb 09 '18 at 09:31
  • I provided [the answer](https://stackoverflow.com/a/48705981/3731501) in duplicate question instead that addresses your concerns, i.e. practical differences between those two methods. Hope this helps. – Estus Flask Feb 09 '18 at 12:36
  • Sometimes I feel like people think Stackoverflow is Google search or something... – RockGuitarist1 Feb 09 '18 at 18:26

1 Answers1

2

Constructor :

The constructor method on an ES6 class (or TypeScript in this case) is a feature of a class itself, rather than an Angular feature. It’s out of Angular’s control when the constructor is invoked, which means that it’s not a suitable hook to let you know when Angular has finished initialising the component.

ngOnInit :

ngOnInit is purely there to give us a signal that Angular has finished initialising the component , The ngOnInit lifecycle hook is a guarantee that your bindings are readily available.

Here is the great article about it in detail : READ

There are lot more discussion upon this like :

Difference between Constructor and ngOnInit

https://blog.angularindepth.com/the-essential-difference-between-constructor-and-ngoninit-in-angular-c9930c209a42

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122