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

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

Transforming an object's type into an array of different types

Looking to create an array of types based on object properties: type T = { a: number | string; b: string | number; c: number; d: boolean; }; Desired Output: [number | string, string | number, number, boolean] Intending to use this as a ...

You cannot set parameters using Angular's httpHeaders post method

Seeking assistance in obtaining the authtoken from RestAPI using a specific method. While the same URL, Parameters, and Headers provide the correct response in Postman, I am encountering a 401 unauthorized error in Angular. Can someone help me identify whe ...

Personalizing the arrow positioning of the Angular8 date picker (both top and bottom arrow)

I am interested in enhancing the design of the Angular 8 date picker by adding top and bottom arrows instead of the default left and right arrows. Can someone guide me on how to customize it? Check out the Angular 8 date picker here ...

Guide on properly specifying mapDispatchToProps in a component's props interface

In my project, I have a connected component utilizing mapStateToProps and mapDispatchToProps along with the connect HOC from react-redux. My goal is to create concise and future-proof type definitions for this component. When it comes to defining types fo ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

If "return object[value1][value2] || default" does not work, it means that value1 is not a recognized property

Within my code, there is an object literal containing a method that retrieves a sub-property based on a specific input. If the lookup fails, it should return a default property. //private class, no export class TemplateSelection { 'bills'; & ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Explanation of Default Export in TypeScript

I recently started learning about JS, TS, and node.js. While exploring https://github.com/santiq/bulletproof-nodejs, I came across a section of code that is a bit confusing to me. I'm hoping someone can help explain a part of the code. In this project ...

A guide to setting a file size limit for image uploads (e.g. limiting to 2MB) using Angular

We are currently working on implementing a maximum size limit of 2mb for images using ng2-file-upload. Below is the code snippet: uploader: FileUploader = new FileUploader({ url: URL, disableMultipart: true }); ... ... OnFileSelected(event) { ...

What is the reason behind Webpack's behavior of loading all files from a folder during lazy loading

I am attempting to dynamically import i18n files using webpack: function getI18n(lang) { return import(/* webpackChunkName "i18n/[request]" */ `./locales/${lang}.json`) .then(/*whatever*/) } However, I have noticed that all the files from the specifi ...

Tips for setting NgForm value within an Observable and verifying its successful implementation

Exploring the functionality of NgForm, I am testing to validate if the value of a form gets updated when the state of the store changes. @ViewChild('form') form: NgForm; ngOnInit() { this.subscription = this.store.select('shoppingList&apos ...

What steps are necessary to integrate barrel file imports with my Angular 2 application?

Following the Angular 2 style guideline 04-10 Create and Import Barrels can be challenging, as it may lead to unexpected file loading issues. When running my app, I noticed that Angular attempts to load a non-existent file named "my-component-name-here.js" ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

The routing functionality in Angular4 encounters issues when the `router.navigate()` method is used within the callback of a

I am currently working on implementing Google Sign In within my Angular4 app, but I have run into an unusual issue with routing after using router.navigate() in the Google Sign In callback function. To help illustrate this issue, I have created a sample d ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

Steps for eliminating the chat value from an array tab in React

tabs: [ '/home', '/about', '/chat' ]; <ResponsiveNav ppearance="subtle" justified removable moreText={<Icon icon="more" />} moreProps={{ noCar ...

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

Tips on sending component values to Host Listener in Custom Directives using Angular 2

I am looking to transmit model values from my HTML template to a custom directive: @Directive({ selector: '[eventlistener]' }) export class EventListener { @Input() value:string = 'Not Defined'; @HostListener('click& ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...