Search code examples
htmlangularenums

How to create checkbox from the enum then get the selected enum value


I'm trying to create a few checkboxes from the enum.

export enum Tags {
   Sword = <any>"Sword",
   Claymore = <any>"Claymore",
   Bow = <any>"Bow",
   Catalyst = <any>"Catalyst",
   Polearm = <any>"Polearm"
}

From this enum is there a way to loop creating checkboxes with Angular? I found these but cannot get the values back. This is in the component.

tagsText = Object.values(Tags);
getHeroByTags(e: any) {
   console.log(e);
}

This is in the HTML.

<li *ngFor="let tag of tagsText">
   <label>
      <input type="checkbox" (click)="getHeroByTags($event)" value="{{tag}}"/>
      {{tag}}
   </label>
</li>

It generates the checkbox with the correct label but doesn't get the enum value in the function getHeroByTags.


Solution

  • You should use event.target.value to get the value of the checkbox.

    getHeroByTags(e:any){
       console.log(e.target.value);
    }
    

    Or even simple, you can just pass the tag to the getHeroByTags method.

    <input type="checkbox" (click)="getHeroByTags(tag)" [value]="tag"/>
    
    getHeroByTags(tag: string){
       console.log(tag);
    }