Allow constants, enums, functions to be used in templates without having to add component members
See original GitHub issueI’m submitting a…
[ ] Regression (a behavior that used to work and stopped working in a new release)
[ ] Bug report
[ ] Performance issue
[ x ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
[ ] Other... Please describe:
Current behavior
Templates cannot refer to anything not directly associated with the component, so you can’t for example do this:
<div *ngIf="user.id === someConstant">
</div>
<div *ngIf="user.status === UserStatus.Active"> <!-- UserStatus is an enum -->
</div>
<div *ngIf="isDevMode()">
</div>
To make this work, I have to declare these as members of my component:
import { someConstant } from './somewhere';
import { UserStatus } from './somewhere';
import { isDevMode } from '@angular/core';
export class MyComponent {
public someConstant = someConstant;
public UserStatus = UserStatus;
public isDevMode = isDevMode;
}
These can quickly clutter the component code, and can’t be used for const enums. For const enums I have to duplicate the entire enum into a constant, which becomes a maintenance headache.
Expected behavior
It would be helpful if I could use constants, enums and functions directly from within the template, without needing to assign them to a component member. Maybe a way of importing variables/types into the HTML, or declaring types in the component that are available to the template. Something like this perhaps:
import { someConstant } from './somewhere';
import { UserStatus } from './somewhere';
import { isDevMode } from '@angular/core';
@Component({
selector: 'app-user-list',
templateUrl: './user-list.component.html',
templateImports: [someConstant, UserStatus, isDevMode]
})
(this particular solution wouldn’t work for const enums, other solutions may be better)
Environment
Angular CLI: 6.1.2
Node: 8.11.1
OS: linux x64
Angular: 6.1.1
Issue Analytics
- State:
- Created 5 years ago
- Reactions:161
- Comments:9 (2 by maintainers)
Top GitHub Comments
This would not work, but the below could:
In addition, non-
const
enums bear the cost of extra generated code (and additional indirection when accessing enum values), which quickly adds up.Using string unions solves that, but IMO enums are nicer because they namespace the values, makes the code easier to read (i.e. easier to find where the values are defined), and are a more familiar pattern for people coming from other languages.
For now we’re still using non-
const
enums but having Angular supportsconst
ones would allow to shave off at least 150kB from our app according to the bundle sizes report, i.e. this issue has concrete performance implications for medium-to-large apps.