繁体   English   中英

从核心模块声明和导出指令,但不触发Angular 7

[英]Directive declared and exported from core module but not triggering Angular 7

大家好,我将用几句话回答我的问题。 我在“核心模块”文件夹中创建了一条指令,并将其添加到声明中并导出到此类模块中。 此模块在App模块(主体模块)中实现。 我在索引页中使用了指令装饰器(此页面在另一个模块页面模块中声明),一切都很好,我没有收到任何错误,但是指令的逻辑是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 { }

的index.html

<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');
  }
}

找到解决问题的方法后,我在顶层(主层)声明了该模块,而不是将其移至pages模块,因为我意识到这是唯一使用的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM