【发布时间】:2019-09-18 09:41:05
【问题描述】:
大家好,我将用几句话继续我的问题。 我在我的核心模块文件夹中创建了一个指令,并将其添加到声明中并在此类模块中导出。该模块在 App Module(主体模块)中实现。我在我的索引页面中使用指令装饰器(此页面在另一个模块页面模块中声明)一切都很好我没有收到任何错误但指令的逻辑没有触发。
我尝试在页面模块中声明该指令及其工作。如果从核心模块中删除指令也会引发错误,这也很奇怪,无法确定类 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 { }
索引.html
<p appHasfunctionality>
index works!
</p>
在这种情况下,元素“p”应该将颜色更改为蓝色。
如您所见,app 模块接收了核心的所有元素,并且 angular 不会抛出任何错误,但逻辑不会触发。
【问题讨论】:
-
您能否尝试以下操作,而不是
el.nativeElement.style.backgroundColor = 'blue'将颜色设置为“蓝色”。 -
嗨,Alexander,已经尝试过了,我显示工作的代码如果我直接在页面模块中声明指令。我认为这是延迟加载?
-
您是否将 AppComponent 的 templateUrl 命名为 index.html?还是您希望您的指令适用于 index.html?
-
你好,yurzui,没有在页面模块级别创建 index.html。
-
您必须在您尝试使用该指令的模板中声明组件的模块中导入 CoreModule
标签: javascript angular typescript angular-directive