How can I properly bind an enum within a dropdown menu in Angular 4?












0














In a dropdown menu, I've used an Enum data structure (Typescript) to store my values. However it seems that the data binding to the object's category field doesn't take place properly and nothing is selected by default. Is there any better solution?



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
}
}


Mapping the enum data type to labels:



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'}
];









share|improve this question
























  • You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
    – trichetriche
    Nov 20 '18 at 9:18












  • And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
    – trichetriche
    Nov 20 '18 at 9:20
















0














In a dropdown menu, I've used an Enum data structure (Typescript) to store my values. However it seems that the data binding to the object's category field doesn't take place properly and nothing is selected by default. Is there any better solution?



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
}
}


Mapping the enum data type to labels:



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'}
];









share|improve this question
























  • You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
    – trichetriche
    Nov 20 '18 at 9:18












  • And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
    – trichetriche
    Nov 20 '18 at 9:20














0












0








0







In a dropdown menu, I've used an Enum data structure (Typescript) to store my values. However it seems that the data binding to the object's category field doesn't take place properly and nothing is selected by default. Is there any better solution?



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
}
}


Mapping the enum data type to labels:



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'}
];









share|improve this question















In a dropdown menu, I've used an Enum data structure (Typescript) to store my values. However it seems that the data binding to the object's category field doesn't take place properly and nothing is selected by default. Is there any better solution?



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
}
}


Mapping the enum data type to labels:



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'}
];






angular typescript data-binding enums






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 11:25









Mohammed Ameen

495




495










asked Nov 20 '18 at 9:12









Janina Alisár

13




13












  • You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
    – trichetriche
    Nov 20 '18 at 9:18












  • And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
    – trichetriche
    Nov 20 '18 at 9:20


















  • You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
    – trichetriche
    Nov 20 '18 at 9:18












  • And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
    – trichetriche
    Nov 20 '18 at 9:20
















You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
– trichetriche
Nov 20 '18 at 9:18






You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects)
– trichetriche
Nov 20 '18 at 9:18














And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
– trichetriche
Nov 20 '18 at 9:20




And to select a value as default, you have to set your ngModel (which you lack on your select) to the default value you want to use.
– trichetriche
Nov 20 '18 at 9:20












2 Answers
2






active

oldest

votes


















0














We can simplify the bind with ngModel, I have create another property to bind with select element and get property to get the vaLue as CategoryEnum



compoenent



  // 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
}


template



<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}}



You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects) as @trichetriche said




demo






share|improve this answer





























    -1














    Yes, set



    <select ... [value]="1">


    where 1 is example default category enum value.



    And use category.value instead whole object category as option value



    <option ... [value]="category.value" >


    and update your .ts file to handle that change.






    share|improve this answer























    • She is using objects as values, not numbers
      – trichetriche
      Nov 20 '18 at 9:20










    • I update answer
      – Kamil Kiełczewski
      Dec 4 '18 at 20:13











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389635%2fhow-can-i-properly-bind-an-enum-within-a-dropdown-menu-in-angular-4%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    We can simplify the bind with ngModel, I have create another property to bind with select element and get property to get the vaLue as CategoryEnum



    compoenent



      // 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
    }


    template



    <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}}



    You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects) as @trichetriche said




    demo






    share|improve this answer


























      0














      We can simplify the bind with ngModel, I have create another property to bind with select element and get property to get the vaLue as CategoryEnum



      compoenent



        // 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
      }


      template



      <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}}



      You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects) as @trichetriche said




      demo






      share|improve this answer
























        0












        0








        0






        We can simplify the bind with ngModel, I have create another property to bind with select element and get property to get the vaLue as CategoryEnum



        compoenent



          // 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
        }


        template



        <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}}



        You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects) as @trichetriche said




        demo






        share|improve this answer












        We can simplify the bind with ngModel, I have create another property to bind with select element and get property to get the vaLue as CategoryEnum



        compoenent



          // 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
        }


        template



        <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}}



        You have to use [ngValue] for options when you want to send non-primitive types (in your case, objects) as @trichetriche said




        demo







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 10:00









        malbarmawi

        5,10331131




        5,10331131

























            -1














            Yes, set



            <select ... [value]="1">


            where 1 is example default category enum value.



            And use category.value instead whole object category as option value



            <option ... [value]="category.value" >


            and update your .ts file to handle that change.






            share|improve this answer























            • She is using objects as values, not numbers
              – trichetriche
              Nov 20 '18 at 9:20










            • I update answer
              – Kamil Kiełczewski
              Dec 4 '18 at 20:13
















            -1














            Yes, set



            <select ... [value]="1">


            where 1 is example default category enum value.



            And use category.value instead whole object category as option value



            <option ... [value]="category.value" >


            and update your .ts file to handle that change.






            share|improve this answer























            • She is using objects as values, not numbers
              – trichetriche
              Nov 20 '18 at 9:20










            • I update answer
              – Kamil Kiełczewski
              Dec 4 '18 at 20:13














            -1












            -1








            -1






            Yes, set



            <select ... [value]="1">


            where 1 is example default category enum value.



            And use category.value instead whole object category as option value



            <option ... [value]="category.value" >


            and update your .ts file to handle that change.






            share|improve this answer














            Yes, set



            <select ... [value]="1">


            where 1 is example default category enum value.



            And use category.value instead whole object category as option value



            <option ... [value]="category.value" >


            and update your .ts file to handle that change.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 20 '18 at 9:21

























            answered Nov 20 '18 at 9:18









            Kamil Kiełczewski

            8,87585788




            8,87585788












            • She is using objects as values, not numbers
              – trichetriche
              Nov 20 '18 at 9:20










            • I update answer
              – Kamil Kiełczewski
              Dec 4 '18 at 20:13


















            • She is using objects as values, not numbers
              – trichetriche
              Nov 20 '18 at 9:20










            • I update answer
              – Kamil Kiełczewski
              Dec 4 '18 at 20:13
















            She is using objects as values, not numbers
            – trichetriche
            Nov 20 '18 at 9:20




            She is using objects as values, not numbers
            – trichetriche
            Nov 20 '18 at 9:20












            I update answer
            – Kamil Kiełczewski
            Dec 4 '18 at 20:13




            I update answer
            – Kamil Kiełczewski
            Dec 4 '18 at 20:13


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389635%2fhow-can-i-properly-bind-an-enum-within-a-dropdown-menu-in-angular-4%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]