Angular 2无法识别自定义指令

问题描述

我创建了一个自定义指令,并将其添加到我的app.module的声明中。但是当我在组件中使用它时,它给我一个错误

嵌入的任何指令均未使用属性绑定hasClaim 模板。确保属性名称拼写正确,并且 所有指令均在“ @ NgModule.declarations” .ng

中列出

这是我创建指令的方式:

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

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: '[hasClaim]'
})
export class HasClaimDirective {

  constructor(
    private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef,private ss: SecurityService,) { }

  @input() set hasClaim(claimType: any) {
    debugger;
    if (this.ss.hasClaim(claimType)) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

这就是我的实现方式:

 <ul class="nav">
      <ng-container *ngIf="securityObject.isAuthenticated">
        <li *ngFor="let menuItem of menuItems" routerLinkActive="active" class="{{menuItem.class}}">
            <a [routerLink]="[menuItem.path]" *hasClaim="'Admin'"> <=== THIS IS THE DIRECTIVE
                <i class="nc-icon {{menuItem.icon}}"></i>
                <p>{{menuItem.title}}</p>
            </a>
        </li>
      </ng-container>
      <ng-container *ngIf="!securityObject.isAuthenticated">
        <li routerLinkActive="active" class="">
          <a routerLink="/login">
          <i class="nc-icon nc-key-25"></i>
          <p>Login</p>
        </a>
        </li>
      </ng-container>
      <ng-container *ngIf="securityObject.isAuthenticated">
        <li routerLinkActive="active" class="" (click)="logout()">
          <a routerLink="/login">
          <i class="nc-icon nc-lock-circle-open"></i>
          <p>logout</p>
        </a>
        </li>
      </ng-container>
    </ul>

enter image description here

enter image description here

解决方法

问题是您要在def convert(string): list1 = [] list1[:0] = string return list1 # Driver code str1 = "ABCD" print(convert(str1)) 中声明该指令,并且要在app.module.ts中声明的组件中使用

如果仅在navbar.component中使用指令,请在NavBarModule.module中声明该指令

否则,您可以创建一个模块,例如navBarModule.module.ts在其中声明和导出指令的位置,并在具有需要该指令的组件的模块中导入

utils.module

在导航模块中

import { NgModule } from '@angular/core';
import {HasClaimDirective} from './hasclaim.directive'


@NgModule({
  declarations: [ HasClaimDirective ],exports:[HasClaimDirective]
})
export class UtilsModule { }
,

仔细观察错误消息:

属性绑定hasClaim未被嵌入式模板上的任何指令使用。确保属性名称拼写正确,并且所有指令都列在“ @ NgModule.declarations” .ng

可能的解决方法1:

看到这一行,他们说了什么:

directives are listed in the "@NgModule.declarations

修复方法是:转到您的 app.module.ts ,然后导入指令,并在导入后将其添加到声明数组中

例如:这是在我的项目中

我在这里输入了代表。

enter image description here

我想您的错误是想告诉您-导入您的指令,然后将其放入app.module.ts的声明数组中

可能的解决方案2:

您不应该在html中的指令前使用星号(*)

根据doc的建议,阅读此文档页面可能会满足您的需求

enter image description here