Skip to content

New rule suggestion: angular hooks need to have access to this #1002

@Samuel-Therrien-Beslogic

Description

Description and reproduction of the issue
Angular lifecycle hooks (and other methods), need to have access to this. So they cannot be arrow functions!

ngOnInit = () => {
  // do something
  // this is never called :(
}

As a workaround, I have been using the no-restricted-syntax rule from eslint, but I might be missing something, and it would be nice to have this rule as a standalone for everyone.

"no-restricted-syntax": [
          "error",
          {
            "selector": "ClassDeclaration:has(Decorator :matches([name=\"Component\"], [name=\"Injectable\"])) :matches(PropertyDefinition[key.name=\"intercept\"], PropertyDefinition[key.name=\"ngOnChanges\"], PropertyDefinition[key.name=\"ngOnInit\"], PropertyDefinition[key.name=\"ngDoCheck\"], PropertyDefinition[key.name=\"ngAfterContentInit\"], PropertyDefinition[key.name=\"ngAfterContentChecked\"], PropertyDefinition[key.name=\"ngAfterViewInit\"], PropertyDefinition[key.name=\"ngAfterViewChecked\"], PropertyDefinition[key.name=\"ngOnDestroy\"]) > ArrowFunctionExpression",
            "message": "Angular hooks need to be functions defined on the prototype: https://github.com/angular/angular/issues/7270#issuecomment-201137617"
  }
]

xref angular/angular#38241

Versions

package version
@angular-eslint/eslint-plugin-template 13.2.1
@angular-eslint/template-parser 13.2.1
@typescript-eslint/parser 5.25.0
ESLint 8.15.0
node 16.13.2
# Please run `npx ng version` in your project and paste the full output here:
 >  NX   Cannot find target 'version' for project 
  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest supported version of the packages and checked my ng version output per the instructions given here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    PRs WelcomeIf a high-quality PR is created for this it will be acceptedpackage: eslint-pluginAngular-specific TypeScript rules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions