[英]Angular: Custom structural directive doesn't work
作為角度教程的一部分,我嘗試創建自定義結構指令。
Google或stackoverflow搜索都能夠提供解決此問題所需的信息。
該代碼如下所示:
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { environment } from 'src/environments/environment.prod';
@Directive({
selector: '[appRole]'
})
export class RoleDirective {
private role: string;
private hasView = false;
get appRole() {
return this.role;
}
@Input()
set appRole(value: string) {
this.role = value;
const access = this.hasRolePermission( value );
if ( access && !this.hasView) {
this.viewContainer.createEmbeddedView( this.template );
this.hasView = true;
} else if ( access && !this.hasView ) {
this.viewContainer.clear();
this.hasView = false;
}
}
constructor(
private template: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
hasRolePermission( role: string ): boolean {
return role === environment.role;
}
}
指令在相應的模塊中導出:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RoleDirective } from './role.directive';
@NgModule({
declarations: [RoleDirective],
imports: [
CommonModule
],
exports: [RoleDirective]
})
export class UserModule { }
在使用的模板下方:
<header>
<h1 appHover="red">Benutzer</h1>
</header>
<main>
<app-user-list [ngStyle]="style">
</app-user-list>
<button *appRole="admin">Administration</button>
<button *appRole="user">Benutzer</button>
</main>
<footer>
<ng-container [ngSwitch]="company">
<img *ngSwitchCase="'omega'" src="../assets/img/logo.jpg" alt="logo">
<img *ngSwitchCase="'alphaAndOmega'" src="../assets/img/alphaAndOmega.jpg" alt="logo">
<img *ngSwitchDefault src="../assets/img/angularLogo.png" alt="angular">
</ng-container>
<img *ngIf="showOmega; else elseBlock" src="../assets/img/logo.jpg" alt="logo">
<button id="logo" (click)="toggleLogo()">
Zeige Logo "Alpha and Omega"
</button>
<ng-template #elseBlock>
<img src="../assets/img/alphaAndOmega.jpg" alt="logo">
</ng-template>
</footer>
<router-outlet></router-outlet>
在AOT編譯期間,我收到一條錯誤消息,該屬性不存在該類型:
ERROR in src\app\app.component.html(8,11): : Property 'admin' does not exist on type 'AppComponent'.
src\app\app.component.html(9,11): : Property 'user' does not exist on type 'AppComponent'.
任何有關如何解決此問題的幫助或指示,將不勝感激。
此致,Patrik
由於您要將字符串傳遞給appRole指令,因此需要用引號引起來-否則,它正在尋找具有該名稱的屬性以提供值。
嘗試
<button *appRole="'admin'">Administration</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.