Home > Blockchain >  Use custom enum in angular template component parameter
Use custom enum in angular template component parameter

Time:07-26

I have a component that has a click handler which takes in an enum type as a parameter and would like to use that enum type in the component html template when the handler is called, however I get a type error:

Argument of type '"ERROR"' is not assignable to parameter of type 'DownloadType'

enum

export enum DownloadType {
  CURRENT = "CURRENT",
  ALL = "ALL",
  ERROR = "ERROR",
}

action-bar.component.ts

onDownload(downloadType: DownloadType) {
  // do stuff
}

action-bar.component.html

<button (click)="onDownload('ERROR')">Download Errors</button>

I have tried supplying the enum value without quotes to the handler as well, but that also did not work ("onDownload(DownloadType.ERROR)")

CodePudding user response:

Per @Eliseo 's comment, just adding a field to the component that is equal to the enum type works

import { DownloadType } from "/path/enums.ts"

@Component({
  templateUrl: "./action-bar.component.html",
})
export class ActionBarComponent {
  // stuff
  DownloadType = DownloadType
  // other component stuff
}

And then just use the enum in the html file as you would use any other enum.

CodePudding user response:

Alternatively to the enum you could simly create a type like this:

export type DownloadType = "CURRENT" | "ALL" | "ERROR";
  • Related