Trouble with implementing a custom attribute directive in Angular 4 and Ionic 3

Hello, I am currently working on implementing a search input field focus using a directive that has been exported from directives.module.ts. The directives.module is properly imported into the app.module.ts file. However, when attempting to use the directive in an ion-searchbar, I encounter the following error message. I am unsure of what I might be overlooking.

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 { }

Answer №1

In order to properly implement the focuser directive, it is necessary to entirely eliminate the DirectivesModule module from the app.module.ts file and instead import it within the module of the specific page where the directive is utilized.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In an Angular Material data table, table headers will always be displayed, even if there is no data

When utilizing the Angular material data table to present product-related information with sorting functionality using matSort, I faced an issue. Even when no data is available, the table headers still remained visible due to the [hidden]="!data" ...

Storing Angular 4 Http Post response data in an object

I'm currently working with Angular 4 in conjunction with an Asp.net web API. I am facing difficulties in reading the properties of my response. This is how my response appears: https://i.stack.imgur.com/NDJCo.png Here is my post request: postLogi ...

Angular 4: Is there a correlation between the level of complexity in componentizing HTML and the difficulty of passing variables to sibling components?

Do you ever wonder if the way you're approaching something is correct? I tend to believe that breaking down an HTML page into as many sub-components as possible is a good practice. For example, let's look at this situation: An existing compone ...

Utilizing Angular's *ngIf directive in conjunction with Observables to handle data retrieved from

Utilizing multiple REST services for data retrieval and altering the value of an Observable in my component code has been a challenge. I've attempted to use *ngIf to toggle the visibility of div tags based on the result, however, the Observable's ...

A step-by-step guide on effectively adopting the strategy design pattern

Seeking guidance on the implementation of the strategy design pattern to ensure correctness. Consider a scenario where the class FormBuilder employs strategies from the following list in order to construct the form: SimpleFormStrategy ExtendedFormStrate ...

Navigating directly to URLs in Angular Universal with iisnode

My issue involves an Angular Universal application. While everything runs smoothly locally with express, and inside of node, deploying the production build to IIS with iisnode results in a 500 Internal Server Error when navigating directly via URL. Unfor ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

Sending data from an element within an ngFor loop to a service module

In my component, I have a loop that goes through an array of different areas with unique IDs. When you click the button, it triggers a dialog containing an iframe. This iframe listens for an event and retrieves data as JSON, then sends it via POST to an IN ...

When running tests on Angular components that interact with Firebase, errors occur, specifically in the creation phase, resulting in a NullInjectionError. However

Currently, I am in the final stages of developing a chat application using Angular and Firebase. Everything appears to be working smoothly until I encountered numerous strange errors during testing. One particular issue is the inability to create certain ...

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

What is the purpose of a Typescript function that returns a function with a generic type?

I recently stumbled upon a perplexing piece of TypeScript code that revolves around the function componentControl. Despite my efforts, I find myself struggling to fully comprehend its purpose and functionality. componentControl: const componentControl: &l ...

Troubleshooting a problematic dependency in Angular with the ngx-favicon package

Could someone please clarify why I am encountering issues when trying to run npm install ngx-favicon? npm install ngx-favicon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi ...

Develop a customized configuration module for managing ESLint, Prettier, and resolving import issues efficiently

Currently, I am developing a configuration npm module for my personal project. This repository includes Prettier, ESLint, tsconfig, and other tools that I have set up. You can find my configuration tools repository here: https://github.com/Seyrinian/seyri ...

Nested HTTP requests in Angular using RxJS: Triggering component update after completion of the first HTTP request

I have a requirement to make two http requests sequentially. The values retrieved from the first call will be used in the second call. Additionally, I need to update my component once the first http request is completed and also update it once the second ...

Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters. import { createSlice, PayloadAction } from ...

Exploring alternative options for routing in Angular2 using auxiliary outlets

I have a folder structure that looks like this: my-app |- src |- app |- private |- private.routing |- public |- public.routing app.routing The contents of the private.routing file are as follows: export const rout ...

Having trouble compiling the Electron App because of a parser error

Struggling to set up a basic electron app using Vue 3 and Typescript. Following the successful execution of certain commands: vue create app_name cd .\app_name\ vue add electron-builder npm run electron:serve Encountering issues when trying to i ...