大家好,我会用几句话恢复我的问题。我在Core Module文件夹中创建了一个指令,并将其添加到声明中并导出到这个模块中。该模块在App Module(主要模块)中实现。我在我的索引页面中使用指令装饰器(此页面在另一个模块页面模块中声明)一切都很好我没有收到任何错误,但指令的逻辑是nos触发。
我已尝试在页面模块及其工作中声明该指令。还有一些非常奇怪的事情,如果从核心模块中删除指令它会抛出错误无法确定类的模块HasfunctionalityDirective哪个是正确的
import { Directive, ElementRef, Renderer2} from '@angular/core';
@Directive({
selector: '[appHasfunctionality]'
})
export class HasfunctionalityDirective{
constructor(
private elem: ElementRef,
private renderer: Renderer2
) {
this.renderer.setStyle(this.elem.nativeElement, 'color', 'blue');
}
}
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HasfunctionalityDirective } from './directives/hasfunctionality.directive';
@NgModule({
declarations: [
HasfunctionalityDirective
],
imports: [
CommonModule,
],
exports: [
HasfunctionalityDirective
]
})
export class CoreModule { }
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CoreModule } from './core/core.module';
@NgModule({
declarations: [
AppComponent,
],
imports: [
CoreModule,
],
bootstrap: [AppComponent]
})
export class AppModule { }
<p appHasfunctionality>
index works!
</p>
在这种情况下,元素“p”应该将颜色更改为蓝色。
正如您所看到的,app模块接收核心的所有元素,而angular不会抛出任何错误,但逻辑不会触发。
您只能在afterviewinit中获得对该元素的引用。试试这个
import { Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
@Directive({
selector: '[appHasfunctionality]'
})
export class HasfunctionalityDirective implements AfterViewInit {
constructor(
private elem: ElementRef,
private renderer: Renderer2
) {
}
ngAfterViewInit() {
this.renderer.setStyle(this.elem.nativeElement, 'color', 'blue');
}
}
找到我的问题的解决方案,我在顶层(主)声明模块,而不是我移动到页面模块,因为我意识到这是唯一使用的地方。