角度:自定义结构指令不起作用

时间:2019-04-01 12:55:08

标签: angular

作为角度教程的一部分,我试图创建一个自定义结构指令。

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'.

对于解决此问题的任何帮助或指示,我们将不胜感激。

诚挚的问候, 帕特里克

1 个答案:

答案 0 :(得分:1)

由于您要将字符串传递到appRole指令中,因此需要将其引号-否则,它将寻找具有该名称的属性以提供值。

尝试

<button *appRole="'admin'">Administration</button>