【问题标题】:angular2 how to access class constants in htmlangular2如何访问html中的类常量
【发布时间】:2018-01-23 06:40:16
【问题描述】:

我在 typescript 类中有一些常量定义为 public static readonly。这包含一些跨应用程序的通用常量。 如何在组件 html 中访问它们? 有没有办法直接在html中使用? {{MyConstantsFactory.Myconstant} 这样的东西会起作用吗?

【问题讨论】:

标签: angular typescript


【解决方案1】:

不,您必须在类的构造函数中本地(使用您的工厂)强制转换它们并像通常使用任何属性一样使用它们

【讨论】:

    【解决方案2】:

    如果你给你的组件添加一个全局变量,你可以像这样访问它:

    @Component({
        template: `<div>MyConstant is {{ myConstanstsFactory.MyConstant }}</div>`
    })
    
    class MyComponent {
       public myConstanstsFactory = MyConstantsFactory;
       ...
    }
    

    【讨论】:

      【解决方案3】:

      您不能从 HTML 访问静态字段,但您可以定义一个 getter 来访问它们:

      export class AppComponent implements OnInit {
      
        public static readonly CONFIG = { a: 1, b: 2 };
      
        get config() {
          return AppComponent.CONFIG;
        }
      
      }
      
      // in HTML
      <div>{{ config | json }}</div>
      

      【讨论】:

        猜你喜欢
        • 2011-11-28
        • 1970-01-01
        • 2016-03-17
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2017-05-21
        相关资源
        最近更新 更多