简体   繁体   中英

enum typescript bug if my string have space

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

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()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM