1

I have another hypothetical question, well kind of ... I was asked to join a new project (using Angular 4+ and Typescript) and I got into a discussion with a colleague. In a Component I have a property and I set the value of the property in the Component / Class constructor method - something like this:

public minDate: Date;
public selectedDate: string;

constructor() {
    this.minDate = this.makeMinDate();
}

makeMinDate() {
    // do stuff
}

I was faced with anger and derision as I was told this was bad practice and the this.minDate should be set (given its value) in the OnInit lifecycle hook, like so

public minDate: Date;
public selectedDate: string;

public ngOnInit(): void {
    this.minDate = this.makeMinDate();
}

makeMinDate() {
    // do stuff
}

"Assigning a value in the constructor was bad practice", I thought that in such a case it wouldn't make a difference. Is setting the this.minDate in the constructor method an not in the OnInit hook bad practice?

Any advice or help is appreciated... I am currently going through the docs to see who is correct.

If I have phrased or asked my question in a confusing or bad way please leave a comment and I will rework the question.

3
  • This could be useful for you: angular.io/guide/lifecycle-hooks#oninit :)
    – AT82
    Oct 26, 2017 at 8:04
  • 2
    If it doesn't make the testing of the component harder, it's perfectly fine. Using ngOnInit can be a better idea if each constructor call ends up making calls to services, that need to be mocked in tests, even for tests that don't care about minDate. You can even use public minDate = makeMinDate()
    – JB Nizet
    Oct 26, 2017 at 8:05
  • 3
    Of course, using ngOnInit would also be mandatory if the value of an input is needed to compute the minDate.
    – JB Nizet
    Oct 26, 2017 at 8:11

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.