The directive does not function properly when used across multiple files

Struggling with @Directives and @Hostlisteners - seeking assistance

The directive added to the input seems unresponsive, failing to trigger any events or console.log(). I'm puzzled and frustrated as there appears to be a missing piece of the puzzle that eludes me.

Here's my project structure:

app
|
|___ components
|   |
|   |___ Autocomplete
|       |___ autcomplete.component.html
|       |___ autcomplete.component.ts
|       |___ autcomplete.component.css
|
|
|___ directives
|   |___ keyboard.directive.ts
|
|___ app.module.ts

In autocomplete.component.html:

<div class="input-field">
    <label [attr.for]="id">{{ label }}</label>
    <input keyboard type="text" [(ngModel)]="inputData" 
           name="inputData" [attr.id]="id"
           class="autocomplete-input" autocomplete="off"/>
</div>

and keyboard.directive.ts:

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

@Directive({
selector: '[keyboard]'
})

export class KeyboardDirective {

    constructor(el: ElementRef) {}

    @HostListener('focus', ['$event']) onFocus(value: string) {
        console.log('Focus caught.');
    }

    @HostListener('keydown', ['$event']) onKeyPressed(e: any) {
        console.log('keydown event);
    }
}

and my app.module.ts looks like this:

import {KeyboardDirective} from '../app/directives/keyboard.directive';

@NgModule({
    declarations: [
        KeyboardDirective
    ],
    providers: [],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA
    ],
    bootstrap: [AppComponent]
})

export class AppModule {}

Directly adding the directive in the component works fine, but placing it in another folder results in issues. Any insights into why this might be happening would be greatly appreciated.

Answer №1

Without seeing your entire code, I can point out some possible mistakes:

1 - Make sure you import the necessary directive in the module where your Autocomplete component is declared. It seems like your component declaration is missing from your code.

2 - If the directive is not in the same module, make sure to import the module where it is declared. Since you mentioned declaring it in appModule, consider creating a separate module for directives.

3 - Don't forget to export the directives in the directives modules to avoid errors about unknown directive/components.

Give these suggestions a try and update your post with any progress!

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

Guide on converting enums in Angular 6

I have been working on translating enums in Angular, but I'm facing a challenge. While I can read and display them in a dropdown menu, translating them is proving to be difficult. Here is an example of my code: export enum test { test1 = '1 - ...

Customizing the appearance of antd Button using emotion and typescript

I've been attempting to customize an antd Button component using emotion in TypeScript, but I encountered an error when trying to implement the styled Button. The error message I received was: Type '{ children: never[]; }' is not assignab ...

React: Dealing with unsuccessful imports

Whenever a device loses internet connection, my app crashes due to an imported component that relies on Google Maps. To address this issue and prevent the app from showing a blank screen, I want to intercept the failed Google Maps import and display an err ...

How can you establish the default value for a form from an Observable?

Check out my TypeScript component below export interface Product{ id?:string, name:string, price:string; quantity:string; tags:Tags[]; description:string; files: File[]; } product$:Observable<Product | undefined>; ngOnIn ...

How can two distinct sachems be returned in an http get request using res.json()?

There are two schemes that I have created: Sales and Abc I would like to send a response that includes the documents for both schemas: router.get('/', function(req, res) { Sales.find(function (err, sales) { if (err) return next(err) ...

JavaScript - Modifying several object properties within an array of objects

I am attempting to update the values of multiple objects within an array of objects. // Using a for..of loop with variable i to access the second array and retrieve values const AntraegeListe = new Array(); for (let i = 0; i < MESRForm.MitarbeiterL ...

Exploring the MEAN Stack for a Fresh Take on Single Page Application Development

Currently, I have implemented the hash location strategy on my Angular 4 client-side application. The refresh functionality works fine in development mode, but when I compile it to production mode using ng build -prod, the refresh feature breaks and the pa ...

Is there a way to verify in Angular whether an image link has a width and height exceeding 1000?

I'm currently working on a function that checks if an image linked in an input field has a width and height greater than 1000 pixels, and is in JPG format. Here's my approach: HTML: <input (change)="checkValidImage(1, product.main_photo)" [ ...

Error: The function createImageUrlBuilder from next_sanity__WEBPACK_IMPORTED_MODULE_0__ is not defined as a valid function

Having some trouble with my Next.js TypeScript project when integrating it with sanity.io. I keep getting an error saying that createImageUrlBuilder is not a function. See screenshot here Here is the code from my sanity module ...

Angular - attaching functions before page navigation - incompatible with HostListener

I'm looking for a way to implement some logic in an angular component that runs before the user navigates away from the page. I've tried a few suggestions found through Google, but so far nothing has worked for me. One approach I attempted involv ...

Resolve cyclic dependency caused by utilizing the useFactory parameter

I am working with an injectable service that utilizes the useFactory attribute to determine whether it should be injected or if an implemented type should be used instead. import { Injectable } from '@angular/core'; import { Router } from ' ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

"Angular throws an error code NG5002 when encountering an invalid ICU message along with an unexpected

Currently, I'm utilizing the most recent release of Angular 17.0.0-next.6, which introduces support for the updated control flow. Interestingly, individuals on Twitter have mentioned that it works flawlessly for them; hence, the issue likely resides w ...

Unable to retrieve selected value from Flowbite-React Datepicker due to malfunctioning props change event

I am encountering an issue with extracting the selected value from the Datepicker component in the flowbite-react library while using it with NextJS. The component is being displayed correctly. I attempted the code below, but it does not return anyth ...

An unconventional approach to conducting runtime checks on Typescript objects

I've been working on a server application that receives input data in the form of JavaScript objects. My main task is to validate whether these data meet certain requirements, such as: having all required fields specified by an interface ensuring th ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

Need help in NestJS with returning a buffer to a streamable file? I encountered an error stating that a string is not assignable to a buffer parameter. Can anyone provide guidance on resolving this issue?

The issue description: I am having trouble returning a StreamableFile from a buffer. I have attempted to use buffer.from, but it does not seem to work, resulting in the error message below. Concern in French language: Aucune surcharge ne correspond à cet ...

Populate an Angular form using @Input to display data retrieved from a Firebase database through a service injection

I've encountered a challenge while working on an Ionic Angular project involving a form. The issue I'm facing is related to a component that serves as a form filled by an Input (Component). The problem seems to be that the form gets populated be ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...