[英]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
}
<div id="adminDiv" *ngIf="hasAccess(RoleType.Admin)">
</div>
這是一種更簡潔的方法。 在您的 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.