1

Do fields need to be initialized using the constructor for angular components? A lot of angular tutorials do:

counter: number;

constructor() {
    this.counter = 1;
}

Instead of just counter: number = 1.

1 Answer 1

4

Both are correct programming wise,

Initialized within the constructor

It would be good practice to initialized within the constructor , it's kind of code separation of declaration + initialization .

That will increase your code readability and you will be sure that all values initialized within the constructor only. and because in the constructor is when the object is created, and it is when the variable should initialized.


Initialized outside the constructor

One issue with initialized using the constructor is , more code to write , when you have alot variable to work with , in that case you should use direct counter: number = 1 , In this case you can check declaration + initialization in single line , but in above case you have to go through 2 steps declaration + initialization

It really matters when you choose initialisation within one of the life cycle hook (E.g. NgOnInit / NgAfterViewInit) vs the constructor. Either it's just a coding style

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.