简体   繁体   English

如何使用 TypeScript 在类中创建静态常量?

[英]How to create a static constant in a class using TypeScript?

How to create an TypeScript static constant in a class?如何在类中创建 TypeScript 静态常量? That mean I can refer a constant without initialize the class.这意味着我可以在不初始化类的情况下引用一个常量。 This is my class:这是我的课:

export class CallTree{
    public static readonly active = 1;
    ............................
}

The component's html is something like the following:组件的 html 类似于以下内容:

 <table mat-table [dataSource]="callTreeList" matSort class="mat-elevation-z8 callTreeList">
    ...............................

  <ng-container matColumnDef="status">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Status</th>
    <td mat-cell *matCellDef="let element" [innerHTML]="(element.status === CallTree.active)?'Active':'Inactive'"></td>
   </ng-container>

The browser console prompt the following error message:浏览器控制台提示如下错误信息:

TypeError: Cannot read property 'active' of undefined 

How can I fix the problem?我该如何解决这个问题? How can I use this constant in the Angular component's html?如何在 Angular 组件的 html 中使用这个常量?

you can import the class and refer the class property in you components.您可以导入类并在组件中引用类属性。

assume you have your constant class in the const.class.ts file假设你在const.class.ts文件中有你的常量类

import { CallTree } from './const.class'

export class AppComponent  {

  name = CallTree.active;    

}

You can declare like this你可以这样声明

export class CallTree{

static readonly: number = 1;

}

https://www.tutorialsteacher.com/typescript/typescript-static https://www.tutorialsteacher.com/typescript/typescript-static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM