如何通过Angular中的属性启用导入到模板组件中的常量而无需代理? [英] How to enable constants imported into component in the template without proxy via properties in Angular?

查看:99
本文介绍了如何通过Angular中的属性启用导入到模板组件中的常量而无需代理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的组件中,我已经导入了一个常量,并且按原样使用它.

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?

推荐答案

使用管道可以解决此问题.我有一个类似下面的管道:

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];
  }
}

并像这样使用它:

{{null | constant:'LuckyNumber'}}

正如@KonradViltersen在评论中提到的那样,我正在考虑使用value而不是args.但是随后Angular Language Service产生了一个主意. 如果将args的类型从string更改为key,语言服务将为您提供自动补全功能,这在拥有大量常量时非常有用.但是,如果将value的类型更改为key,则模板中只会出现一些错误,告诉您类型不匹配且不会出现运行时错误.如何使用它成为一种喜好.

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.

您也遇到枚举问题.

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];
  }
}

可以像

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

它将为Hard提供自动完成功能,但不为Complexity

It will provide autocomplete for Hard but not for Complexity

Stackblitz

这篇关于如何通过Angular中的属性启用导入到模板组件中的常量而无需代理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆