Modify the BehaviorSubject upon clicking or focusing on the input

I have created a directive for an input field. I want to trigger a flag in another component when the input is clicked or focused upon.

@Directive({
  selector: '[appDatepicker]'
})
export class DatepickerDirective implements DoCheck{

  constructor(private el: ElementRef, private transport: TransportData<boolean>) {

   }

  ngDoCheck(): void {
    let element = this.el.nativeElement;
    if (element.onfocus !== null || element.onclick !== null) {
      this.transport.setListValue(true);
    } else {
      this.transport.setListValue(false);
    }
  }
}

Here is my input with the appDatepicker directive applied.

<input appDatepicker>

Upon loading the page, the attributes onfocus and onclick are initially null as expected. However, the issue arises when clicking on the input field - nothing happens. How can I listen for input events within the directive in order to set the BehaviorSubject?

Answer №1

If you want to handle host element events within a directive, you can make use of the @HostListener decorator.

@HostListener('focus', ['$event'])
focus(event) {
  console.log('Element has gained focus');
}

@HostListener('click', ['$event'])
click(event) {
  console.log('Element was clicked!');
}

@HostListener('blur', ['$event'])
blur(event) {
  console.log('Element lost focus');
}

Check out a demonstration here: https://stackblitz.com/edit/angular-bg7rpl

Emitting Custom Events

You also have the ability to emit your own events from the directive if desired.

directive.ts

@Output() myfocus: EventEmitter<void> = new EventEmitter<void>();

@HostListener('focus', ['$event'])
focus(event) {
  this.myfocus.emit();
}

component.html

<input appDatepicker (myclick)="onClick()" />

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

Testing services in Angular that rely on TranslateService with unit tests

How should I utilize the TranslateService in unit tests for a service? The TranslateService is typically used in the service class like this: export class ErrorControllerService { constructor(public translate: TranslateService) { } ... } I at ...

Is there a way to streamline the import process for material-ui components?

Is there a shortcut to condense all these imports into one line? As a newcomer to react, I've noticed that every component must be individually imported, especially when it comes to CSS components. Could you provide me with a suggestion on how to st ...

The form inputs within the modal are unresponsive to clicks

I recently began using bootstrap modals and had a separate register/login page from the index. I thought incorporating the login/register form into modals would be a good idea. However, inside the modal, all the inputs are not clickable - only accessible v ...

Creating a star-based rating feature through directive implementation

Can anyone help me figure out why my static star rating system using angularjs/ionic is not showing up on the screen? I've been struggling with it and would appreciate some guidance. service.html <ion-list> <ion-item ng-repeat="busine ...

Customizing the appearance of selection dropdown options in React

Is it possible to customize the styling of the choices in a React input dropdown? For instance, I am interested in creating an autocomplete dropdown that presents the options neatly arranged in columns. Essentially, I want to design a dropdown data grid t ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

What steps should I take to enable TypeScript IntelliSense to recommend correct suggestions within discriminated unions?

I am working on creating a checkbox UI component based on a design in Figma. The outline variant is specified to only be compatible with the large size, while the solid variant can be used with all sizes. As a result, I am trying to build an interface whe ...

Creating a node.js function that can be used with OracleDB

I'm currently delving into learning nodeJS, but I'm facing a roadblock and can't seem to figure out what's causing the issue. Even the Debugger isn't providing much help. Any assistance or guidance would be greatly appreciated. The ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

What is the proper way to utilize $apply and $watch in the Angularjs 1.4.10 Directive Structure?

`.directive('counter', function counter() { return { scope: {}, bindToController: { count: '=' }, controller: function () { function increaseCount() { this.count++; } function decreaseCo ...

Guidelines for choosing and uploading a file using Ionic

Is there a way to upload a PDF file to a server using the $cordovaFileTransfer plugin? I currently have an input field like this: <input type="file" onchange="angular.element(this).scope().fileNameChanged(this)"> How can I retrieve the pathForFile ...

Error: The method .map is not a valid function in this context

I've decided to build a small To-Do app in order to enhance my knowledge of ReactJS and React Hooks. However, I'm facing an issue with the list.map() function that I'm using. The error message keeps saying that it's not a function, but ...

How can I customize the styling of Angular Material Datepicker?

I am currently incorporating the Angular Material Datepicker into various parts of my application. One particularly important usage is a legacy one that must remain untouched for the proper functioning of the application. This legacy Datepicker is extensiv ...

Updating a React event as it changes with each onChange event

Let's address a disclaimer before diving into the issue - for a quick look, visit this pen and type something there. The Scenario This is the JSX code snippet used in my render method: <input value={this.state.value} onChange={this.handleCh ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

Node.js bypasses unit test validation

As a beginner in BDD with Node.js, I have a controller function defined as follows: var getUser = function(username, done) { console.log('prints'); User.findOne({ 'local.username': username }, function (err, user) { ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

Creating a data structure that consists of pairs of elements, inspired by the alignment of domino bricks, using TypeScript syntax

My goal is to establish a type alias in TypeScript that allows all values which are arrays of Domino pairs, where each pair connects like domino bricks: Pair<A,B> connects with Pair<C,D> only if B = C. For example: const chain1: DominoChain = ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

The global variable remains unchanged after the Ajax request is made

I am attempting to utilize AJAX in JavaScript to retrieve two values, use them for calculations globally, and then display the final result. Below are my code snippets. // My calculation functions will be implemented here var value1 = 0; var v ...