Search code examples
angulartypescriptinterfacengoninit

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.


Solution

  • 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).