【发布时间】:2019-12-11 20:31:42
【问题描述】:
在 Angular 8 中,我创建了一个新模块并放入了一个新指令。但在执行时没有任何反应(编译正常)。
我输入了控制台登录指令,因此以不同的方式查看它是否已执行但从未调用过构造函数。
<button button-confirmation></button>
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ButtonConfirmationComponent } from './component/button-confirmation.component';
import { ButtonConfirmationDirective } from './directive/button-confirmation.directive';
import {
ConfirmationService,
DomService
} from './services';
@NgModule({
declarations: [
ButtonConfirmationComponent,
ButtonConfirmationDirective
],
imports: [
CommonModule
],
providers: [
ConfirmationService,
DomService
]
})
export class ButtonConfirmationModule { }
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[button-confirmation]'
})
export class ButtonConfirmationDirective {
constructor(private el: ElementRef) {
console.log(el, 'test');
el.nativeElement.style.backgroundColor = 'yellow';
}
}
@NgModule({
declarations: [
...
],
imports: [
@NgModule({
declarations: [
...
],
imports: [
...
ButtonConfirmationModule
另一方面,如果我尝试使用组件 ButtonConfirmationComponent,我得到了错误
'app-button-confirmation' 不是已知元素: 1.如果'app-button-confirmation'是一个Angular组件bla bla bla
这个组件移动到应用程序到模块并且之前工作过(内部没有改变)。
我关注了很多文章和角度网站,都是一样的,所以我变得疯狂,为什么模块中的指令不起作用?为什么组件不理解?
也许它有帮助,我使用 Material Angular。
感谢您的帮助。
【问题讨论】:
-
您是否将指令附加到 HTML 元素?
标签: angular angular-directive angular8 angular-module