Angular @Output Named With An on Prefix
ID |
javascript.angular_output_on_prefix |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Naming Convention |
Language |
JavaScript |
Tags |
angular, framework, naming |
Description
Reports an Angular @Output whose binding name is on or begins with an on prefix:
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
// Bad — the template reads (onSave)="save()".
@Output() onSave = new EventEmitter<void>();
// Bad — the alias carries the prefix instead.
@Output("onCancel") cancel = new EventEmitter<void>();
}
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
// Good
@Output() save = new EventEmitter<void>();
@Output() cancel = new EventEmitter<void>();
}
The name checked is the one a template writes: the alias when the decorator declares one, the property name otherwise.
Rationale
on is the DOM property convention — onclick is where a handler is stored. Angular does not use it: an output is subscribed to, and the template already spells that out with parentheses. (onSave) therefore reads as "on on save", and the prefix carries nothing the parentheses do not.
It also misleads. A property named onSave looks like a native handler slot, which is what a reader scanning the class for DOM wiring will take it for.
Remediation
Name the output after the thing that happened, as a verb in the past tense or a noun:
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
@Output() saved = new EventEmitter<void>();
@Output() valueChange = new EventEmitter<string>();
}