简体   繁体   中英

I can't figure out why Angular component class add implements onInit interface

When you create a component through the "ng g component ~" command, the component class automatically implements 'OnInit' interface.

The following snippet shows how a component can implement this interface to define its own initialization method.

@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
  ngOnInit() {
    // ...
  }
}

In the Angular documentation above, it says that the interface is meant to define its own initialization method,

Even if you omit the 'implement OnInit' syntax, there is no problem in defining it through the ngOnInit () {} syntax.

I am not sure why I have to write it.

An interface (similar to java) is a contract between a component and an interface implementation. Angular developer push to use OnInit like initialization block (and not the component constructor).

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