【问题标题】:Directive declared and exported from core module but not triggering Angular 7从核心模块声明和导出但不触发 Angular 7 的指令
【发布时间】: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


【解决方案1】:

找到了我的问题的解决方案,我在顶层(main)上声明了模块,而不是我移动到 pages 模块,因为我意识到这是唯一使用的地方。

【讨论】:

    【解决方案2】:

    你只能在 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');
      }
    }
    

    【讨论】:

    • 嗨 jcuypers,我尝试了 oninit、afterviewinit,结果是一样的
    • 奇怪,这基本上是一样的:stackblitz.com/edit/angular-jv9szt?embed=1&file=src/app/…。顺便说一句,我看不到 BrowserModule 的导入。有吗?
    • 是的,但我在我的应用程序中使用了问题中提到的层,给我时间,我将上传一个带有架构的 stackbkitz
    • 当然是通用模块。浏览器模块等需要在应用程序级别加载,以使任何基本的 Angular 东西都能正常工作和使用
    • @jcuypers 我在这里遇到了一些问题,stackoverflow.com/q/56076337/8662236 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2020-08-27
    • 1970-01-01
    • 2019-01-31
    • 2019-04-07
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多