在下拉菜单中,我使用了枚举数据结构(Typescript)来存储我的值。然而,与对象类别字段的数据绑定似乎没有正确发生,并且默认情况下未选择任何内容。有没有更好的解决办法?
export enum CategoryEnum {
EXAMPLECAT1 = 1,
EXAMPLECAT2 = 2,
EXAMPLECAT3 = 3,
EXAMPLECAT4 = 4
}
@Component({
selector: 'category',
template: `
<label for="appCategory">Example Category: </label>
<select class="form-control" id="exampleCategory" required
(change)="parseValue($event.target.value)"
(ngModelChange)="changeSelectedType($event)">
<option *ngFor="let category of categoryTypes"
[value]="category">{{category.type}}</option>
</select>
`
})
export class CategoryComponent {
private selectedCategoryType: CategoryEnum
private categoryTypes;
constructor(){
this.categoryTypes = CategoryMapping
}
parseValue(value : string) {
this.selectedCategoryType = AppCategoryEnum[value];
}
//Logging: Change Selected Product type callback
private changeSelectedType(event: any) {
console.log(event); //object, depends on ngValue
console.log(this.selectedCategoryType); //object, depends on ngValue
}
}
将枚举数据类型映射到标签:
export const CategoryMapping = [
{ value: ExampleCategoryEnum.EXAMPLECAT1, type: 'Example 1' },
{ value: ExampleCategoryEnum.EXAMPLECAT2, type: 'Example 2'},
{ value: ExampleCategoryEnum.EXAMPLECAT3, type: 'Example 3'},
{ value: ExampleCategoryEnum.EXAMPLECAT4, type: 'Example 4'}
];
我们可以用
ngModel
简化绑定,我创建了另一个属性来与 select 元素绑定并获取属性来获取值 CategoryEnum
组件
// I have change this to public just for demo
public get selectedCategoryType():CategoryEnum {
return this.selectedValue ? this.selectedValue.value: null;
}
private categoryTypes;
public selectedValue:any;
constructor() {
this.categoryTypes = CategoryMapping;
this.selectedValue = this.categoryTypes[2]; // set default value
}
模板
<select class="form-control" id="exampleCategory" required [(ngModel)]="selectedValue" >
<option></option>
<option *ngFor="let category of categoryTypes"
[ngValue]="category">{{category.type}}</option>
</select>
<br>
selectedCategoryType : {{selectedCategoryType | json}}
当您想要发送非原始类型(在您的情况下为对象)时,必须使用 [ngValue] 作为选项,正如 @tricheriche 所说
首先创建将枚举转换为对象数组的函数
convertEnumToKeyValue(t:any):{value:any,label:any}[]
{
let keys=Object.keys(t);
let valueIndex=(keys.length/2);
let keyArray:{value:any,label:any}[]= [];
for(let i=0;i<valueIndex;i++)
{
keyArray.push({value:keys[i],label:keys[i+valueIndex]});
}
return keyArray;
}
then call this like
enum Colors
{
Red=1,
Green=2,
Blue=3
}
最后称之为
colorTypes= convertEnumToKeyValue(Colors)
现在在您的选择中使用 colorTypes 和 ngFor
是的,设置
<select ... [value]="1">
其中
1
是示例默认类别枚举值。
并使用
category.value
代替整个对象 category
作为选项值
<option ... [value]="category.value" >
并更新您的 .ts 文件以处理该更改。