簡體   English   中英

Angular2 - 如何在 *ngIf 中使用字符串枚舉

[英]Angular2 - How to use string enums with *ngIf

在 Angular 中使用*ngIf時如何將enum傳遞給函數?

我有以下代碼:

export enum RoleType {
    User='User',
    Admin='Admin'
}

組件功能

public hasAccess(role: RoleType) {
   //check role type and return true or false
}

組件 html

<div id="adminDiv" *ngIf="hasAccess('Admin')">
</div>

當我構建它時,它一直在抱怨。 它無法將字符串轉換為枚舉,有沒有辦法解決這個問題?

正如@Buczkowski 建議的那樣,您可以這樣做:

export enum RoleType {
    User = 'User',
    Admin = 'Admin'
}

成分

RoleType = RoleType; // This way you can access its properties from the template.

public hasAccess(role: RoleType) {
    //check role type and return true or false
}

組件 html

<div id="adminDiv" *ngIf="hasAccess(RoleType.Admin)">
</div>

StackBlitz 示例

這是一種更簡潔的方法。 在您的 component.ts 中執行以下操作

allRoleTypes = RoleType;

並在您的 html 中

*ngIf="role===allRoleTypes.User"

您不需要編寫任何方法。

將其作為字符串獲取,然后將其轉換為 RoleType。

public hasAccess(role: string): boolean {
const roleAsEnum: RoleType = RoleType[role];

return ...
}

您不應該在模板中使用帶參數的函數,而是執行以下操作:

.ts文件中聲明 var isAdmin ,並在創建組件時對其進行初始化,檢查用戶是否為 admin:

isAdmin = false;
ngOnInit() {
    this.isAdmin = this.checkIfUserAdmin(...)
}

*ngIf使用它:

<div id="adminDiv" *ngIf="isAdmin">
</div>

您可以使用另一個 var,例如 .ts 文件中的AdminTest ,並在ngOnInit掛鈎中為其設置一個值。

你應該有類似的東西:

.ts :

AdminTest = false;

ngOnInit() {
    this.AdminTest = this.checkRole()
}

checkRole() {
    // ...
}

.html :

<div id="adminDiv" *ngIf="AdminTest"></div>

出現錯誤是因為您在需要枚舉時傳遞字符串。 正如其他人所建議的那樣,有多種方法可以處理它,其中之一是:

  private hasRole(role: string) {
    console.log(role == RoleType.admin);
    console.log(role == RoleType.user);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM