Angular 自定义指令没有任何效果

Angular custom directive doest not have any effect

我以这种方式在我的 angular 应用程序中创建了一个自定义的简单指令:

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

@Directive({
  selector: '[testDirective]'
})
export class TestDirective implements OnInit {

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    console.log('directive works');
    this.elementRef.nativeElement.style.backgroundColor = 'red';
  }

}

我在app.module.ts中是这样声明的:

import { TestDirective } from './shared/component/tree/test.directive';

@NgModule({
  imports: [
    ...
  ],
  declarations: [TestDirective,...]
 ...
})
...

最后是我在模板中使用此指令的方式:

<p testDirective>This is just for example</p>

我希望在我的浏览器控制台中看到 directive works,并且 <p> 的背景颜色也会更改为红色。但是 none 他们工作,也没有任何错误。只是指令不生效!我不知道出了什么问题。我的代码有什么错误吗?

请注意,我的项目使用 angular 的 7.2.12 版本。

对于可能遇到相同问题的任何人,正如 JB Nizet 在评论中所说,问题是 我正在使用来自另一个模块的指令.我将声明从 app.module 移到了相关模块,它现在可以工作了。

感谢所有特别帮助我的人 JB Nizet 的有益评论。