1

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?

6
  • are you using TimeValueDirective directly inside of the template of AppComponent ? if not - directive should be imported in the Shared module - module which is imported everywhere Commented Feb 15, 2021 at 9:41
  • CLI added the directive in the main module app.module.ts . I assume is avaliable to all madules. Commented Feb 15, 2021 at 9:46
  • no, it doesn't work like that in angular. all declarations are shared only in the module. also the ones in exports section are shared when you are importing the shared module into one of your modules Commented Feb 15, 2021 at 9:53
  • In my project I have AppModule and then 2 more modules SettingsPageModule and HomePageModule that are lazy loaded but I can't find a SharedModule in the project structure generated by CLI. If I include the directive into the SettingsPageModule nothing changes. Commented Feb 15, 2021 at 10:01
  • 2
    if this directive is used inside of SettingsPageModule components, then import it there. also use it like [appTimeValue]. you will see not found error in this case, rather just not working directive Commented Feb 15, 2021 at 10:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.