来自共享模块的Angular 8指令不起作用

问题描述 投票:0回答:1

大家好!我正在尝试制定一个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

angular typescript angular2-directives
1个回答
0
投票

您的类应实现OnInit生命周期挂钩(不是强制性的,但是一种很好的做法),方法应为ngOnInit()

export class HasPermissionDirective implements OnInit {

  constructor(private el: ElementRef) { }

  ngOnInit() {
    console.log('--------------------------------------------------');
  }

}

在Eliseo提到的共享模块中,您应该只导入公共模块,而不要导出它。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.