简体   繁体   中英

Angular 2 directive, oninit and ngoninit

Sometimes we declare in constructor and ngoninit. can you please help me in finding the difference.

export class NavComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

The constructor is the default method of the class that is executed when the class is instantiated. It ensures proper initialization of all the properties of the class and all of its subclass if any.

While the ngOnInit() is the lifecycle hook provided by Angular which only indicates the creation of a component by Angular. It is basically an interface that is implemented by the class.

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 and not perform any business logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM