Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable in Angular component. In ngOnInit or in variable declaration?

Tags:

angular

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?

like image 856
Miguel Moura Avatar asked Mar 07 '19 13:03

Miguel Moura


2 Answers

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
   }

}
like image 98
KShewengger Avatar answered Oct 19 '22 11:10

KShewengger


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.

like image 1
Sats Avatar answered Oct 19 '22 09:10

Sats