【问题标题】:Can't bind to Angular 9 custom directive无法绑定到 Angular 9 自定义指令
【发布时间】:2020-03-25 15:59:59
【问题描述】:

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

不幸的是,我明白了

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

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

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

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

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

    【讨论】:

    • 我不会这么想的!效果很好。发送虚拟啤酒?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    相关资源
    最近更新 更多