Angular @Output Alias
ID |
javascript.angular_output_alias |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Best Practice |
Language |
JavaScript |
Tags |
angular, best-practice, framework, naming |
Description
Reports an Angular @Output that renames the property it binds:
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
// Bad — the template listens on saved, the class emits on saveEvent.
@Output("saved") saveEvent = new EventEmitter<void>();
// Bad — the same alias, written as an options object.
@Output({ alias: "cancelled" }) cancel = new EventEmitter<void>();
}
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
// Good
@Output() saved = new EventEmitter<void>();
@Output() cancelled = new EventEmitter<void>();
}
Rationale
An alias gives one event two names. The template listens on one, the class emits on the other, and neither name leads to the other by search — so the pair has to be kept in step by memory.
It fails in both directions:
-
Renaming the property leaves every template untouched and silently still correct, so the two names drift apart until nobody can tell which is canonical.
-
Renaming the alias breaks the templates with no compile error, because a template binding is resolved by string.
An event name that reads badly from the outside is better fixed by renaming the property, which fixes both sides at once.
Remediation
Give the property the name the template should listen on, and drop the alias:
import { Component, EventEmitter, Output } from "@angular/core";
@Component({ selector: "app-editor", template: "" })
export class EditorComponent {
@Output() saved = new EventEmitter<void>();
}
Where the alias exists to keep an old public name working during a migration, keep it only for as long as the migration lasts and remove it with the last consumer.