How to enable constants imported into component in the template without proxy via properties in Angular?

前端 未结 1 834
旧时难觅i
旧时难觅i 2020-12-22 13:34

In my component, I have imported a constant and I\'m using it as is.

import { NullGuid } from \"src/app/models/constants\";
...
@Component({ ... })
export cl         


        
相关标签:
1条回答
  • 2020-12-22 14:27

    I have a workaround for that with using pipes. I have a pipe something like below:

    import { Pipe, PipeTransform } from '@angular/core';
    import * as constants from "./constants";
    
    type key= keyof typeof constants;
    
    @Pipe({
      name: 'constant'
    })
    export class ConstantPipe implements PipeTransform {
      transform(value: any, args:key): any {
        return constants[args];
      }
    }
    

    And use it like this :

    {{null | constant:'LuckyNumber'}}
    

    EDIT: As @KonradViltersen mentioned in the comments i was thinking to use value instead of args. But then an idea came with the Angular Language Service. If you change args type from string to type key Language service will provide you auto completion which is good when you have large amount of constants. But if you change values type to key you will only have some error in your template that will tell you about type mismatch and no runtime errors. It becomes a preference how you use it.

    Also problem you are having stands with enums too.

    import * as enums from './enums';
    
    type key = keyof typeof constants;
    type enumKey = (keyof typeof enums) ;
    
    
    @Pipe({
      name: 'enum'
    })
    export class EnumPipe implements PipeTransform {
      transform<T extends enumKey, R extends keyof typeof enums[T]>(value: T, args: R): typeof enums[T][R] {
        return enums[value][args];
      }
    }
    

    Which can be used like

    {{ 'Complexity' | enum : 'Hard' }}
    

    It will provide autocomplete for Hard but not for Complexity

    Stackblitz

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