0

I have a problem wit my enum

I write enum with string and a browse my enum in *ngFor

But if my string have a space the page display me 2 element

this is my enum:

export enum ComponentCategory {
   FormControls = <any> 'Form   Controls',
   Containers = <any> 'Containers' ,
   Boxes = <any> 'Boxes',
   DataPresentation = <any> 'DataPresentation',
   Layout = <any> 'Layout',
   Miscellaneous = <any> 'Miscellaneous',
}

And for exemple, FormControls is display twice like FormControls and Form Controls

Who can fix this ?

Thanks

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
ouanounou
  • 53
  • 1
  • 10

1 Answers1

1

You don't have to explicitly state a string representation of the enum value in typescript.

You can just have:

export enum ComponentCategory {
  FormControls,
  Containers,
  Boxes,
  DataPresentation,
  Layout,
  Miscellaneous
}

To get the enum members as strings you can then use (See this SO for source):

for (var enumMember in ComponentCategory ) {
   var isValueProperty = parseInt(enumMember, 10) >= 0
   if (isValueProperty) {
      console.log(ComponentCategory [enumMember]);
   }
}

to use with *ngFor...

function getEnumNames(){
    var names: Array<string> = new Array<string>();
    for (var enumMember in ComponentCategory ) {
       var isValueProperty = parseInt(enumMember, 10) >= 0
       if (isValueProperty) {
          names.push(ComponentCategory [enumMember]);
       }
    }
    return names.map(name => name.replace(/([A-Z])/g, ' $1').trim());
}

// in html 
<div *ngFor="let name of getEnumNames()">
Zze
  • 18,229
  • 13
  • 85
  • 118
  • thanks to reply me but i want have a space in Form Control who can be display this if my enum is not a string – ouanounou May 31 '17 at 08:52
  • @ouanounou I have updated the code which now adds a space before all capitals in Enum names.. i.e. `FormControls => Form Controls && DataPresentation => Data Presentation` – Zze May 31 '17 at 08:56
  • @ouanounou glad I could help - I think that this is a better method than defining a string for each enum member as it's a double handle if you do. – Zze May 31 '17 at 09:00
  • @ouanounou Please accept this as the correct answer if it solved your issue :) – Zze May 31 '17 at 09:03