简体   繁体   中英

Angular 8+ - do I need to implement the OnInit function in my components if I am not planning to override it?

I'm working on a project with Angular 8.

I noticed that when I generate components with the command line that they come with OnInit.

eg

export class SideDrawerComponent implements OnInit {

    constructor(private sideDrawerService: SideDrawerService) { }

    public ngOnInit(): void { }

    public close() {
        this.sideDrawerService.closeDrawer();
    }

}

As I am not going to override the function, do I need it there?

No. You can remove it and the OnInit interface.

From the docs :

The hooks give you the opportunity to act on a component or directive instance at the appropriate moment, as Angular creates, updates, or destroys that instance. If you implement this method in your component or directive class, Angular calls it shortly after checking the input properties for that component or directive for the first time.

So it isn't mandatory, but will be triggered if you include it.

Also if you so wish to include a lifecycle hook (eg. ngOnInit ) then implementing the corresponding interface ( OnInit ) isn't mandatory. The interface is only there to guide the users for type checks and typos. In theory you could include all the lifecycle hook functions without implementing their interface counterparts.

See here more info.

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