Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does angular-cli generate ngOnInit with no typing for the function result?

I have a component generated by angular-cli and the resulting code for the .ts file has:

ngOnInit() {
}

instead of

ngOnInit(): void {
}

My tslint is configured to always want typedefs present, but the cli generates code without typedefs - that is my issue.

Is there a way to configure the cli to always set the required typedefs or are my only options are to disable this tslint check or fix it manually?

like image 812
FMFlame Avatar asked Sep 04 '17 21:09

FMFlame


People also ask

What is the difference between ngOnInit () and constructor () of a component?

The constructor() should only be used to initialize class members but shouldn't do actual "work". So we should use constructor() to setup Dependency Injection, Initialization of class fields etc. ngOnInit() is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.

When ngOnInit is called?

ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

Is ngOnInit required?

It is only beneficial in the case of dependency injection and initialization of the class field. That being said, the compiler should actually avoid writing the work on Constructor. ngOnInit is a better place to write work code that is required at the time of class instantiation.

What is the difference between ngOnInit and ngOnChanges?

ngOnChanges vs ngOnInit: ngOnInit is called only once during component initialization. ngOnChanges event is executed each time whenever the value of the input control in the component has been modified. ngOnChanges event is called before the ngOnInit() event.


1 Answers

Angular CLI uses blueprints to generate artifacts, and there is a directory @angular/cli/blueprints in your node_modules. For example, there is a subfolder component/files/path where you can find a template for the component generation. The Angular CLI team promises to allow creating custom blueprints in the future, but as of today, you can't just modify the template.

If you just need to add void to the method signature, do it manually or disable the corresponding tslint rule.

The other hacky way would be to use the library angular-cli-tools for template generation ( see https://github.com/littleuniversestudios/angular-cli-tools), but since you just want to add the void return type just do it manually.

like image 113
Yakov Fain Avatar answered Oct 10 '22 22:10

Yakov Fain