最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - How to create checkbox from the enum then get the selected enum value - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited 22 hours ago Yong Shun 51.2k6 gold badges35 silver badges63 bronze badges asked yesterday rheza 555rheza 555 919 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

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);
}
发布评论

评论列表(0)

  1. 暂无评论