How to initialize Enum types in Angular and use them in templates
Enum types are sometimes initialized and used as-is in templates because they are more readable when used as-is in templates.
For example
import { Component } from '@angular/core';
enum Sample {
Tokyo = '東京',
Osaka = '大阪',
Hukuoka = '福岡'
}
@Component({
selector: 'app-root',
template:
`
<p>{{place}}</p> <!-- Hard to know what it means. -->
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
public place1:Sample = Sample.Tokyo;
}
This is an example of storing an enumerator of type Enum in a variable and displaying it.
The typeof can be used to initialize the Enum.
<Variable Name>: typeof <Enum Type> = <Enum Type>
This will put the type Enum in the variable name.
You can use variables as follows
import { Component } from '@angular/core';
enum Sample {
Tokyo = '東京',
Osaka = '大阪',
Hukuoka = '福岡'
}
@Component({
selector: 'app-root',
template:
`
<p>{{place.Tokyo}}</p><!-- You can use enum types as they are. -->
<p>{{place.Osaka}}</p><!-- You can use enum types as they are. -->
<p>{{place.Hukuoka}}</p><!-- You can use enum types as they are. -->
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
public place: typeof Sample = Sample; // Use the typeof keyword
}
It would be easier to understand the enum type declarations if they were made in a separate file and imported.



コメント