Currently, I am facing an issue with data binding in a dropdown menu using an Enum data structure in Typescript. The object's category field is not being selected by default. Is there a better solution to overcome this problem?
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
}
}
To map the enum data type to labels, the following code snippet can be used:
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'}
];