【发布时间】:2019-04-22 16:45:46
【问题描述】:
在下拉菜单中,我使用了 Enum 数据结构 (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'}
];
【问题讨论】:
-
当您想发送非原始类型(在您的情况下为对象)时,您必须使用
[ngValue]选项 -
要选择一个默认值,您必须将您的
ngModel(您在选择中缺少)设置为您要使用的默认值。
标签: angular typescript data-binding enums