英文:
In Angular 14 and PrimeNG, how do I set the value of a radio button to be the key of an enum?
问题
我正在使用Angular 14。我已经定义了这个枚举...
export enum Color {
RED = 'Red Color',
BLUE = 'Blue Color'
}
我有一个PrimeNg单选按钮,我想将单选按钮的值设置为枚举的键(例如,RED),所以我尝试了以下代码:
<p-radioButton
#red
name="color"
[value]="Color.RED"
formControlName="color"
></p-radioButton>
以下是相关的服务代码:
public Color() {
return Color;
}
然而,单选按钮的值被设置为"Red Color",我想要的值是"RED"。如何正确设置语法以实现这一目标?
英文:
I'm using Angular 14. I have defined this enum ...
export enum Color {
RED = 'Red Color',
BLUE = 'Blue Color'
}
I have a PrimeNg radio button where I want to set the value of the radio button to be the key of the enum (e.g. RED), so I tried
<p-radioButton
#red
name="color"
[value]="Color().RED"
formControlName="color"
></p-radioButton>
Here is the relevant service code
public Color() {
return Color;
}
However, the value of the radio button is getting set to "Red Color" and I want the value set to "RED". What's the proper syntax for making this happen?
答案1
得分: 1
1- 在您的组件中,将枚举声明如下:
readonly colors: typeof Color = Color;
2- 创建一个管道,用于获取给定枚举值的键:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {
transform(value: any, enumObject: any): string {
return Object.keys(enumObject).find((key: string) => enumObject[key] === value) || '';
}
}
3- 在您的模板中,使用 enumKey 管道来获取枚举值的键:
<div class="p-field-radiobutton">
<p-radioButton name="color" [value]="colors.RED | enumKey: colors" formControlName="color"></p-radioButton>
<label for="color">RED</label>
</div>
通过采用这种方法,您声明了 colors 变量来保存对 Color
枚举的引用,这使您能够在模板中访问枚举键。enumKey
管道用于获取枚举值的键,它接受 colors.RED 值和 colors 枚举作为参数。
英文:
1- In your component, declare your enum as follows:
readonly colors: typeof Color = Color;
2- Create a pipe that retrieves the key of a given enum value:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {
transform(value: any, enumObject: any): string {
return Object.keys(enumObject).find((key: string) => enumObject[key] === value) || '';
}
}
3- In your template, use the enumKey pipe to retrieve the key of the enum value:
<div class="p-field-radiobutton">
<p-radioButton name="color" [value]="colors.RED | enumKey: colors" formControlName="color"></p-radioButton>
<label for="color">RED</label>
</div>
By following this approach, you declare the colors variable to hold a reference to the Color
enum, which allows you to access the enum keys in your template. The enumKey
pipe is used to retrieve the key of the enum value, and it takes the colors.RED value and the colors enum as arguments.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论