无法绑定到 Angular 9 自定义指令

Can't bind to Angular 9 custom directive

我想创建自己的身份验证指令,当用户没有所需角色时隐藏内容。

不幸的是,我得到了

Error: Template parse errors:
Can't bind to 'appHasRole' since it isn't a known property of 'div'.

我遵循了每一个教程,每一个堆栈溢出问题,似乎都没有帮助。

我已经创建了指令:

import {Directive, ElementRef, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {AuthService} from '../../../security/auth.service';

@Directive({
  selector: '[appHasRole]'
})
export class HasRoleDirective {

  role: string;

  constructor(private element: ElementRef,
              private templateRef: TemplateRef<any>,
              private viewContainer: ViewContainerRef,
              private authService: AuthService) { }

  private updateView() {
    if (this.checkPermission()) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

  private checkPermission() {
    // logic for determining role
  }

  @Input()
  set hasRole(val) {
    this.role = val;
    this.updateView();
  }
}

因为我有多个模块,所以我创建了 SharedModule

import {NgModule} from '@angular/core';
import {HasRoleDirective} from './directives/has-role.directive';

@NgModule({
  declarations: [HasRoleDirective],
  exports: [HasRoleDirective]
})
export class SharedModule {
}

然后在我的主页模块中导入指令(在app.module中也试过了)

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HomeComponent} from './home/home.component';
import {SharedModule} from '../shared/shared.module';

@NgModule({
  declarations: [HomeComponent],
  imports: [
    CommonModule,
    ...
    SharedModule
  ]
})
export class HomeModule {
}

最后,使用 home.component.html

中的指令
<div class="button-group" *appHasRole="['admin']">
...

只需在 @Input 中添加 appHasRole,因为它正在寻找 hasRole 属性。

如果 @Input 没有参数 Angular 查找具有 propertyName 的属性。如果您将参数传递给 @Input,Angular 将查找具有传递的参数值的属性。

@Input('appHasRole') 
   set hasRole(val) {
       this.role = val;
       this.updateView();
    }