【问题标题】:Angular directive imported but not working properlyAngular 指令已导入但无法正常工作
【发布时间】:2020-04-29 14:52:03
【问题描述】:

我使用的是 Angular 版本 7.3.7。我创建了一个指令,但它不能正常工作。指令示例:

import { Directive, OnInit } from '@angular/core';

@Directive({
  selector: '[matchHeight]'
})
export class MatchHeightDirective implements OnInit {

  constructor() { }


  ngOnInit() {
    console.log("this will be work", "color: red");
  }

}

并在shared.module.ts 上导入我的指令。

import { MatchHeightDirective } from './directives/match-height.directive';

const pipes = [DateFormatPipe, SecondToTime, HighlightSearch, TimeFormatPipe];
const components = [
  MatchHeightDirective,
];
@NgModule({
  declarations: [pipes, components],
  imports: [
    CommonModule,
  ],
  providers: [DraggableService],
  exports: [
    CommonModule,
    components,
  ],
})
export class QmsSharedModule {}

并像这样使用它:

<div class="row" matchHeight></div>

但结果没有任何效果。我究竟做错了什么 ?对此有何建议?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    declarations: [pipes, components],

    由于管道和组件已经是数组,因此您的声明现在是一个包含 2 个数组的数组。

    你可以修改为:

    declarations: [...pipes, ...components],

    它应该可以工作。

    【讨论】:

    • 还有你的exports: [CommonModule, ...components]
    • 如果这不起作用,可能会放一个 stackblitz 来看看还有什么可能导致这个问题。
    【解决方案2】:

    将管道和指令从它们的数组中取出。

    【讨论】:

      【解决方案3】:

      还将管道、指令和组件导出到共享模块

      @NgModule({
        declarations: [...COMPONENTS, ...PIPES, ...DIRECTIVES],
        imports: [
          CommonModule,
        ],
      
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        exports: [CommonModule, ...COMPONENTS, ...PIPES, ...DIRECTIVES]
      })
      

      并更改样式以进行验证

      export class MatchHeightDirective {
      
        constructor(el: ElementRef) {
          el.nativeElement.style.color = 'red';
        }
      

      组件.html

      <p matchHeight>Color change </p>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-26
        • 2016-03-25
        • 1970-01-01
        • 1970-01-01
        • 2010-12-30
        • 2017-03-15
        相关资源
        最近更新 更多