How to enable constants imported into component in

2020-02-16 05:02发布

问题:

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

import { NullGuid } from "src/app/models/constants";
...
@Component({ ... })
export class TheComponent implements OnInit {
  constructor(private service: SomeService) { this.proxy = NullGuid; }
  ...
  proxy: string = NullGuid;
}

In the template, I can reach the service like this.

<div>{{this.service.getStuff()}}</div>

However, I can't do the same with the constant unless it's declared as shown above. Can I somehow expose the imported constant without declaring a proxy property for it?

回答1:

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