How to initialize Enum types in Angular and use them in templates

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.

Angular でEnum型を初期化してテンプレートで使用する方法

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL