Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I pass an enum value as a variable to a function in the Angular html file?

I have this enum I would like to use in my html file:

export enum CartAction {
  ADD = 'ADD',
  REMOVE = 'REMOVE',
}

Currently, it is used in the component ts file as

 async cartAction(action: CartAction): Promise<void> {
    if (action === CartAction.ADD) {
    }
    if (action === CartAction.REMOVE) {
    }
  }

And I’d like to be able to use the enum in the html file like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<button (click)="cartAction(someCondition? CartAction.ADD : CartAction.REMOVE )">text</button>

I get the following error:

Property 'CartAction' does not exist on type 'MyPage'. 
Did you mean 'someOtherAction'?ngtsc(2551)

How can I solve this?

>Solution :

To use anything in your template files it needs to be public (protected as of Angular 15) to be accesable, which imports are not.

What I used to do is unwrap the enum in my component:

protected cartActions = CartActions;

with that you should be able to use it as follows:

<button (click)="cartAction(someCondition? cartAction.ADD : cartAction.REMOVE )">text</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

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

Continue reading