Ove*_*nez 5 typescript angular2-directives angular
大家好!我正在尝试制作 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('--------------------------------------------------');
}
}
Run Code Online (Sandbox Code Playgroud)
// 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 { }
Run Code Online (Sandbox Code Playgroud)
//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 {}
Run Code Online (Sandbox Code Playgroud)
// dashboard.component.html
<h6 [permission]="permission" class="h2 text-white d-inline-block mb-0" >Default</h6>
Run Code Online (Sandbox Code Playgroud)
请帮我!!T_T
你的类应该实现 OnInit 生命周期钩子(不是强制性的,但是一个好的实践)并且该方法应该是ngOnInit()
export class HasPermissionDirective implements OnInit {
constructor(private el: ElementRef) { }
ngOnInit() {
console.log('--------------------------------------------------');
}
}
Run Code Online (Sandbox Code Playgroud)
在 Eliseo 提到的共享模块中,您应该只导入公共模块而不是导出它。
归档时间: |
|
查看次数: |
1749 次 |
最近记录: |