Angular @Input Alias
ID |
javascript.angular_input_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 @Input that renames the property it binds:
import { Component, Input } from "@angular/core";
@Component({ selector: "app-field", template: "" })
export class FieldComponent {
// Bad — the template writes labelText, the class reads label.
@Input("labelText") label = "";
// Bad — the same alias, written as an options object.
@Input({ alias: "isRequired" }) required = false;
}
import { Component, Input } from "@angular/core";
@Component({ selector: "app-field", template: "" })
export class FieldComponent {
// Good
@Input() label = "";
@Input() required = false;
}
Rationale
An alias gives one binding two names. The template author sees one, the class author sees 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.
The reason an alias is usually reached for — the property name reads badly from the outside — is better answered by renaming the property, which fixes both sides at once.
Remediation
Give the property the name the template should use, and drop the alias:
import { Component, Input } from "@angular/core";
@Component({ selector: "app-field", template: "" })
export class FieldComponent {
@Input() labelText = "";
}
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.