In Angular 8, i created a fresh module and put a new directive in. But at execution time nothing happen (compile is ok).
I putted console log in directive so see in different manner if it's executed but never, constructor never called.
<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
In other side, if i try ti use the component ButtonConfirmationComponent, i got the error
'app-button-confirmation' is not a known element: 1. If 'app-button-confirmation' is an Angular component bla bla bla
This component moved to the app to the module and worked before (nothing changed inside).
I followed lot of articles and angular site, all the same way, so i become crazy, why directive in module does'nt work ? Why the component not understanded ?
Maybe it helps, i use Material Angular.
Thanks for the help.
Any Module/Components/Pipe/Directive
in order to be seen and used by any Module, it need to be import/declare in its @NgModule class decorator, and it only visible to that module. ( It important to know that Components/Pipe/Directive can only be declared one time in only one module of the whole apps )
So in your case the ButtonConfirmationComponent
, ButtonConfirmationDirective
only visible to ButtonConfirmationModule
, but not be seen by the AppModule
.
Export the ButtonConfirmationComponent
and ButtonConfirmationModule
from your ButtonConfirmationModule
so whichever Module import ButtonConfirmationModule
, those two also be visible to them for use.
In your ButtonConfirmationModule
:
exports : [
ButtonConfirmationComponent,
ButtonConfirmationDirective
]