enum value is not properly evaluated in Angular 9 template

1.3k Views Asked by At

app.component.html

<div *ngFor="let file of files">
 <p>value : {{file.type}}</p>
 <p>bool : {{file.type === FileAccessType.ENTRY_CREATE}}
</div>

app.component.ts

export class AppComponent{
 files : FileAccess[];
 FileAccessType : FileAccessType;
}

file-access.ts

export interface FileAccess {
   path: string;
   type: FileAccessType;
   timestamp: number;
}

file-access-type.ts

export enum FileAccessType{
   ENTRY_CREATE,
   ENTRY_DELETE,
   ENTRY_MODIFY
}

the boolean comparison in template does not work as expected

{{file.type === FileAccessType.ENTRY_CREATE}} //always gives false

ref : stackblitz

2

There are 2 best solutions below

0
On

In app.component you should declare your enum variable like this readonly FileAccessType = FileAccessType;

1
On

Angular components cannot infer types as enums to HTML markdows.
So, as @Oleksii mentioned, you should declare an internal variable to store the type, then, Angular is able to evaluate from the HTML and access the enum's values.

*.html

<div *ngFor="let file of files">
    <p> Value : {{ file.type }} </p>
    <p> Bool : {{ file.type === fileType.ENTRY_CREATE }}
</div>

*.ts

export class FilesComponent {

  fileType = FileAccessType; // Type assign
  files = [...files]; // This is just mocked data

  constructor() {}

}

Alternatively, you can delegate the responsability of the condition to the component, like so

export class FilesComponent {

  files = [...files]; // This is just mocked data

  constructor() {}

  isCreateType = (file: FileAccess) => file.type === FileAccessType.ENTRY_CREATE;
}

Now, you don't have to expose the enum to the HTML

<div *ngFor="let file of files">
    <p>value : {{ file.type }}</p>
    <p>bool : {{ isCreateType(file) }}
</div>