Cannot approach Typescript enum within HTML

前端 未结 5 437
生来不讨喜
生来不讨喜 2021-01-31 13:03

I made an enum with Typescript to use in MyService.service.ts MyComponent.component.ts and MyComponent.component.html.

export enum ConnectionResult {
    Succes         


        
相关标签:
5条回答
  • 2021-01-31 13:35
    import MyEnum from enums;  
    

    .... Declarate var ....

    public myEnum = MyEnum;
    

    and in html use:

    <div *ngIf="xxx === myEnum.DATA"> ... </div>
    
    0 讨论(0)
  • 2021-01-31 13:36

    You can just add the enum to your component as property and use the same name of the enum (Quarters) in your templates:

    enum Quarters{ Q1, Q2, Q3, Q4}
    
    export class AppComponent {
       quarter = Quarters.Q1
       Quarters = Quarters
    }
    

    In your template

    <div *ngIf="quarter == Quarters.Q1">I=am only visible for Q1</div> 
    

    The reason why this works is that the new porperty is basically of this type:

    TileType: typeof TileType
    
    0 讨论(0)
  • 2021-01-31 13:39

    You can bind as text if enum defined as below (those values won't enforce a json string value coming from API)

      export enum SomeEnum {
          Failure,
          Success,
      }
    

    In .ts file

    public status: SomeEnum;

    In .html

    <div *ngIf="status == 'Success'">

    Another way, tested in Angular 8+ is to have enums with numbers

      export enum SomeEnum {
          Failure = 0,
          Success = 1,
      }
    

    In .ts file

    public status: SomeEnum;

    In .html

    <div *ngIf="status == 1">

    0 讨论(0)
  • 2021-01-31 13:49

    You will have to write it in the following way in .ts file.

    enum Tenure { day, week, all }
    
    export class AppComponent {
        tenure = Tenure.day
        TenureType = Tenure
    }
    

    And now in html you can use this like

    *ngIf = "tenure == TenureType.day ? selectedStyle : unSelectedStyle"
    

    I hope it is more clear now. :)

    0 讨论(0)
  • 2021-01-31 13:53

    The scope of the template is limited to the component instance members. If you want to refer to something it needs to be available there

    class MyComponent {
      public get connectionResult(): typeof ConnectionResult {
        return ConnectionResult; 
      }
    }
    

    In the HTML you can now use

    *ngIf="connectionResult.Success"
    

    See also Angular2 access global variables from HTML template

    0 讨论(0)
提交回复
热议问题