【发布时间】:2020-04-24 11:23:33
【问题描述】:
大家好!我正在尝试制作一个 Angular 8 自定义指令,但它对我不起作用,浏览器控制台没有显示任何错误,但我没有可视化我留在代码中的更改或 console.logs,它是如果该指令从未被调用。请有人帮助我!非常感谢。我有这个,我做错了什么?
// has-permission.directive.ts
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
@Directive({
selector: '[permission]'
})
export class HasPermissionDirective {
constructor(private el: ElementRef) { }
@Input() permission: string;
OnInit() {
console.log('this.permission->', this.permission)
console.log('text', this.el.nativeElement.textContent += 'It is working');
console.log('--------------------------------------------------');
}
}
// shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HasPermissionDirective } from '../directives/has-permission.directive'; //<-- My directive
@NgModule({
declarations: [HasPermissionDirective], //<-- Declaring
imports: [ ],
exports: [
HasPermissionDirective, //<-- exporting
CommonModule,
]
})
export class SharedModule { }
//dashboards.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ComponentsModule } from '../../components/components.module';
import { BsDropdownModule } from 'ngx-bootstrap';
import { ProgressbarModule } from 'ngx-bootstrap/progressbar';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AlternativeComponent } from './alternative/alternative.component';
import { RouterModule } from '@angular/router';
import { DashboardsRoutes } from './dashboards.routing';
import { SharedModule } from '../../shared/shared.module'; //<-- Here
@NgModule({
declarations: [DashboardComponent, AlternativeComponent],
imports: [
CommonModule,
ComponentsModule,
BsDropdownModule.forRoot(),
ProgressbarModule.forRoot(),
TooltipModule.forRoot(),
RouterModule.forChild(DashboardsRoutes),
SharedModule, //<-- Here
],
exports: [DashboardComponent, AlternativeComponent]
})
export class DashboardsModule {}
// dashboard.component.html
<h6 [permission]="permission" class="h2 text-white d-inline-block mb-0" >Default</h6>
请帮帮我!! T_T
【问题讨论】:
-
我看到了一个“奇怪的东西”。 1.- 您在 sharedModule 中导出“CommonModule”-我认为您需要删除它,2.- 您是否从“@angular/platform-browser”导入 {BrowserModule};在您的主模块中-不在问题中-?
-
是的,你也可以,我会从那里删除它。非常感谢!
-
您的帖子比在模块内共享指令的角度文档要好,谢谢!
标签: angular typescript angular2-directives