Search code examples
angulartypescriptionic-frameworkionic3angular2-directives

Angular 4 / ionic 3 custom attribute directive not working


Hi I am trying to focus on a search input field. I have created a directive for that. It hs been exported from directives.module.ts. Also I have directives.module imported into app.module.ts. Whenever I try to use the directive in ion-searchbar it gives the following error. I don't know what am I missing.

Can't bind to 'focuser' since it isn't a known property of 'ion-searchbar'.

directives.module.ts

import { NgModule } from '@angular/core';
import { FocuserDirective } from './focuser/focuser';
@NgModule({
    declarations: [FocuserDirective],
    imports: [],
    exports: [FocuserDirective]
})
export class DirectivesModule {}

focuser.ts

import {Directive, Renderer, ElementRef} from "@angular/core";

/**
 * Generated class for the FocuserDirective directive.
 *
 * See https://angular.io/api/core/Directive for more info on Angular
 * Directives.
 */
@Directive({
  selector: '[focuser]' // Attribute selector
})
export class FocuserDirective {

  constructor(public renderer: Renderer, public elementRef: ElementRef) {}

    ngOnInit() {
      //search bar is wrapped with a div so we get the child input
      const searchInput = this.elementRef.nativeElement.querySelector('input');
      setTimeout(() => {
        //delay required or ionic styling gets finicky
        this.renderer.invokeElementMethod(searchInput, 'focus', []);
      }, 0);
    }

}

app.module.ts

import { DirectivesModule } from '../directives/directives.module';


export function provideSettings(storage: Storage) {

  return new Settings(storage, {
    option1: true,
    option2: 'Ionitron J. Framework',
    option3: '3',
    option4: 'Hello'
  });
}

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AutoCompleteModule,
    CalendarModule,
    DirectivesModule,
    IonicModule.forRoot(MyApp),
    IonicStorageModule.forRoot()
  ],
  exports: [
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    Api,
    User,
    SplashScreen,
    StatusBar,
    Constants,
    { provide: Settings, useFactory: provideSettings, deps: [Storage] },
    // Keep this to enable Ionic's runtime error handling during development
    { provide: ErrorHandler, useClass: IonicErrorHandler },
    BoxProvider,
    TellersProvider,
    CheckoutProvider,
    CommonProvider,
  ]
})
export class AppModule { }

Solution

  • You need to remove DirectivesModule module completely from the app.module.ts file and imports it inside the page's module where you use that directive (i.e. focuser).