数组与枚举重复,用于分配和列出帖子标签

时间:2019-02-17 01:09:37

标签: angular typescript

在Angular和TypeScript中,如何创建可以在html文件中迭代并可以通过ts文件中的枚举访问的标签数组?

我目前正在做什么:

// used in my ts file for assigning tags to posts
enum EPostTags {
    tech        = 'Tech News',
    sport       = 'Sport News',
    culture     = 'Culture News',
}

// used in my html file for listing all tags for the filter function
public postTags = [
    'Tech News',
    'Sport News',
    'Culture News',
];

// all my posts including tags
public posts = [
    {
        title: "The world's most interesting post",
        tags: [ EPostTags.tech, ] // so that I get errors in VSCode if I misspell the tag
    },
]

HTML

Filter by: 
<span *ngFor="let tag of postTags" (click)="filterPostsByTag(tag)">
    {{ tag }}
</span>

有什么方法可以对标签数组/枚举使用一个而不是两个定义?

2 个答案:

答案 0 :(得分:1)

您可以访问返回Array<EPostTags>的函数,而不必尝试访问组件中的列表:

export class AppComponent {

  public getList(): Array<EPostTags>{
    let arr: Array<EPostTags> = [];
    for (let e in EPostTags){
       // Get the designated string values as defined in the enum.
       arr.push(EPostTags[`${e}`]);
    }

    return arr;
  }

  // all my posts including tags
  public posts = [
    {
      title: "The world's most interesting post",
      tags: [EPostTags.tech,] // so that I get errors in VSCode if I misspell the tag
    },
  ]

}

HTML:

<span *ngFor="let tag of getList()" (click)="filterPostsByTag(tag)">
    {{ tag }}<br>
</span>

这是一个有效的示例:https://stackblitz.com/edit/angular-4hde6h

答案 1 :(得分:1)

您可以使用Object.values来获取枚举字符串值:

public postTags = Object.values(EPostTags) as EPostTags[];

有关演示,请参见this stackblitz