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?

3
  • Please go through this link: stackoverflow.com/questions/35763730/… Commented Feb 9, 2018 at 9:31
  • I provided the answer in duplicate question instead that addresses your concerns, i.e. practical differences between those two methods. Hope this helps. Commented Feb 9, 2018 at 12:36
  • Sometimes I feel like people think Stackoverflow is Google search or something... Commented Feb 9, 2018 at 18:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.