8

On an Angular 7 application I have the following component:

export class ListComponent implements OnInit {

  visible: boolean;

  ngOnInit() {
    this.visible = false;
  }

  toggle() {
    this.visible = !this.visible
  }

}

And on the view I have:

<table *ngIf="visible">
  Table content
</table>

Is there any difference between setting the initial value of visible inside ngOnInit or in variable declaration, e.g:

visible: boolean = false;

Which approach is better?

Roy
  • 7,811
  • 4
  • 24
  • 47
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • Hi, I think setting an initial value of a variable at the time of declaration is the better approach. – AddWeb Solution Pvt Ltd Mar 07 '19 at 13:24
  • 1
    Possible duplicate of [Difference between Constructor and ngOnInit](https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit) – Igor Mar 07 '19 at 13:48

2 Answers2

5

When you already knew the data you're assigning in a variable, it is best to initialize them upon declaration

@Component({...})
export class ChildComponent {

   visible: boolean = false;

}

But if your variable is dependent to another service or function, then you need to specify it inside the ngOnInit not on the constructor

"Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

"ngOnInit() is better place to "start" - it's where/when components' bindings are resolved."

-Pardeep Jain

@Component({...})
export class ChildComponent {

   visible: boolean;

   constructor(private sampleService: SampleService) {}

   ngOnInit() {
      this.visible = this.sampleService.isVisible;     // May it a plain boolean or an Observable that you need to subscribe
   }

}
KShewengger
  • 7,853
  • 3
  • 24
  • 36
  • 1
    Yup, basically: **If you know the starting value** for the var, init it when you declare. **If you need to _get_ the value** via either an input, or some logic, set it in `ngOnInit` or another lifecycle hook. There is also a case where you might want something to be `undefined` until declared, i.e. table array is undefined which results in a unique UI look, until a http request returns data. Final; it is usually bad practice to init variables in the `constructor` of a class. – Pix3l Mar 07 '19 at 15:33
  • Yes, I agree :) – KShewengger Mar 08 '19 at 00:23
  • The question is about class definition vs constructor though, not constructor vs ngOnInit like the answer you refer to. – paddotk Jun 17 '20 at 12:42
1

Since constructor is called by JavaScript engine and not by Angular. ngOnInit is part of lifecycle called by Angular and is called after the constructor is executed.

In constructor angular initializes and resolved all the members of the class.

You can perform any initial action in ngOnInit Method.

Sats
  • 1,913
  • 1
  • 15
  • 21