Use Lifecycle Interface in Angular 2
Asked Answered
P

2

6

What exactly does this rule effectuate?

"use-life-cycle-interface": true,
Parimutuel answered 12/8, 2016 at 12:28 Comment(0)
M
3

It's not a built-in tslint rule. It's a rule that's defined by codelyzer.

The GitHub repo has a video (that I've not watched), but little documentation. Fortunately, the author has implemented tests, so it's possible to infer what the use-life-cycle-interface rule does from its test descriptions:

it(`should fail, when a life cycle hook is used without implementing it's interface`, ...
it(`should fail, when life cycle hooks are used without implementing their interfaces`,  ...
it(`should fail, when some of the life cycle hooks are used without implementing their interfaces`, ...
Megrim answered 12/8, 2016 at 22:17 Comment(1)
also absolutely needles for me, I use intensively the ng2-templates for WebStorm from JohnPapa and they would be invalid after this rule :)Parimutuel
D
18

it simply means that you have to add the implements keyword for every lifecycle hook you use,

while this is not necessary for angular to recognize and use the hooks, it is much better for code clarity and maintenance.

example:

// don't forget the import
import { AfterViewInit } from '@angular/core';
// you have to have this implements statement 
export class YourComponent implements AfterViewInit {
  // if you want to use this hook
  ngAfterViewInit() {
    // your code...
  }
}
Dollie answered 5/10, 2017 at 9:16 Comment(3)
How would this help as far as maintenance is concerned?Exorbitant
@HlawulekaMAS when your component is several hundred lines of code and your ngAfterViewInit() method is burried deep inside, it's much better to have the interface so you know for sur you have this method is implemented without any guess or serching. For big projects this kind of confidence in your code is needed because you have much more constraints to worry about.Dollie
Wow, I was tempted to argue that you could just search for the keyword but your argument makes more sense especially the "being sure" aspect of it. Thanks for such a thoughtful contribution.Exorbitant
M
3

It's not a built-in tslint rule. It's a rule that's defined by codelyzer.

The GitHub repo has a video (that I've not watched), but little documentation. Fortunately, the author has implemented tests, so it's possible to infer what the use-life-cycle-interface rule does from its test descriptions:

it(`should fail, when a life cycle hook is used without implementing it's interface`, ...
it(`should fail, when life cycle hooks are used without implementing their interfaces`,  ...
it(`should fail, when some of the life cycle hooks are used without implementing their interfaces`, ...
Megrim answered 12/8, 2016 at 22:17 Comment(1)
also absolutely needles for me, I use intensively the ng2-templates for WebStorm from JohnPapa and they would be invalid after this rule :)Parimutuel

© 2022 - 2024 — McMap. All rights reserved.