Search code examples
angularionic-frameworkdirective

Ionic custom directive is Ignored by Angular


I created a custom directive in ionic

ionic g directive directives/time-value

My code is

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

@Directive({
    selector: '[appTimeValue]',
})
export class TimeValueDirective implements OnInit{

    @Input('appTimeValue') myStyles: any;

    constructor() { 
      console.log("I'm here");
    }
    ngOnInit(): void {
      console.log("I'm here");
  
    }
}

then I tried to use the directive

<ion-input type="text" name="fineColazione" [(ngModel)]="fineColazione" appTimeValue></ion-input>

Ionic is ignoring my directive.

the CLI added the directive in the module declaration

@NgModule({
  declarations: [
    AppComponent,
    TimeValueDirective,
  ],
  entryComponents: [],
  imports: [
    CommonModule,
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    FormsModule
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}

How can I make the directive work?


Solution

  • TimeValueDirective should be declared in the same module, as the one that contains the component, which uses that directive. also it is a good practice to make SharedModule with all reusable components/directives/pipes inside of the application and import this module everywhere.