Ways to eliminate toggle event in Angular

I've been doing a lot of research online, but all the solutions I find are using jquery. I'm still getting the hang of Angular and Typescript. I found this and this to be unhelpful. I built a monthpicker from scratch, which has a simple and clear process. When I click on the input field, a popup containing all the months opens up. Something like this:

https://i.sstatic.net/qgZui.png

This popup is actually using p-overlay from the primeng library. Here is my code snippet.

monthpicker.component.html

<textbox 
  (click)="openMonthpicker.toggle($event)">
</textbox>

<p-overlayPanel class="dropdown" #openMonthpicker>
    HTML CODE TO DISPLAY THE MONTHS
</p-overlayPanel>

My monthpicker component is editable, meaning you can input dates through the keyboard. However, I want the popup to close when entering dates. I added this line of code in the textbox:

<textbox 
  ...
  (keydown)="openMonthpicker.off($event)">
</textbox>

It seems that the off function is not working. I also tried using remove, but I'm not sure what function to use to close the popup. Can anyone assist me with this issue?

PS: I also went through TypeScript Event Handlers.

Answer №1

If you want to hide the overlay, use the hide method. It is recommended to maintain a flag to keep track of the overlay's state due to multiple keydown calls.

Check out the demo here

Component

export class AppComponent {

  datePickerOpen = false;

  openDatePicker(event, element) {
      element.toggle(event);
      this.datePickerOpen = true;
    }
  
    closeDatePicker(event, element) {
      if (this.datePickerOpen) {
        element.hide(event);
        this.datePickerOpen = false;
      }
    }
  }

Template

<textarea
  (click)="openDatePicker($event, openMonthpicker)"
  (keydown)="closeDatePicker($event, openMonthpicker)">
</textarea>

<p-overlayPanel class="dropdown" #openMonthpicker>
    HTML CODE FOR DISPLAYING MONTHS
</p-overlayPanel>

Remember to call the hide method on the overlay reference when handling the keydown event.

Answer №2

One way to toggle the picker is by utilizing the (change) function bound to an event.

Here is an example implementation:

<textbox 
  ...
  (change)="togglePicker = true">
</textbox>

I hope this solution is useful to you!

Answer №3

Here is a simple solution for you.

<p-overlayPanel class="dropdown" #openMonthpicker>
    HTML CODE FOR SHOWING LIST OF MONTHS
</p-overlayPanel>

In your code, you have assigned #openMonthpicker as a reference. So, when implementing the months, simply use openMonthpicker.hide() on the click of a month. The hide method is available to toggle it off, which is exactly what you want.

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

Acquiring the appropriate type from a type object using generics in TypeScript

I am working with an enum export const trackingKeys = { Form: 'form', Video: 'video', } as const I also have a type that assigns a type property to each key export type TrackingPropertiesByKey = { [trackingKeys.Form]: { bar : num ...

Analyzing the list of paths that are passed to the function

I am looking for assistance in creating an asynchronous "getTypes" function that can analyze a list of paths and return an array describing the type of content in each path. The function should handle all cases efficiently and in case of any errors during ...

"Enhance Your XYChart with a Striking Background Image Using Amchart

let chart = am4core.create("chartdiv", am4charts.XYChart); chart.background.image = am4core.image("/static/img/bar-chart.png") I'm attempting to apply a background image to my chart in Amchart, but unfortunately it's not di ...

Issues arise with User obj's utilization of the Instagram API

After setting up my Instagram developer account, I was able to obtain the client_secret and client_id. Authentication went smoothly for my own user (myusername), and I received an access_token. However, when attempting to utilize this endpoint TOKEN] Fo ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

How can I dynamically modify the class name of a specific element generated during an iteration in React when another element is clicked?

My goal is to dynamically add a class to a specific element within a table row when a user clicks a remove button. The desired behavior is to disable the entire row by adding a "removed" class to the containing row div. The challenge is that there are mult ...

Transform a Mobx observable map into a JavaScript array

I am working with a component that receives the value of "form.$('userProfile').fields" as a prop, which is an observable map. The structure of this map can be seen in the console.log screenshot below: class Location extends React.Component<* ...

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...

Ways to speed up the disappearance of error messages

There is a minor issue that I find quite annoying. The validation error message takes too long (approximately 3 seconds) to disappear after a valid input has been entered. Let me give you an example. https://i.sstatic.net/8UKrm.png Do you have any tips o ...

issue with brightcove player's complete event not triggering upon video replay

I have a videoplayer with an event listener added in an onTemplateReady function. Upon completion of the video, I want to replay it: videoPlayer.addEventListener(brightcove.api.events.MediaEvent.COMPLETE, completedCallback); function completedCallback(){ ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

The attribute 'status' is not found in the 'ServerResponse' type (TS2339)

I've attempted to develop an interface and install React types, but the only way it seems to work is when I write the code in JavaScript. However, within a TypeScript project, I encounter this error: Property 'status' does not exist on typ ...

Is there a way to manipulate the src value using jQuery or JavaScript?

var fileref = document.createElement('script'); fileref.setAttribute("type","text/javascript"); fileref.setAttribute("src", "http://search.twitter.com/search.json? q="+buildString+"&callback=TweetTick&rpp=50"); ...

The combination of Object.keys() and the find function

Having trouble figuring out why I'm getting an error when attempting to use ES6 .find on the following data in order to retrieve the record with id number 3. { {id:10,title:'Dairy & Eggs'} {id:7,title:'Laundry & Household'} {id ...

CombineReducers takes all the reducer content and unpacks it into a single reducer

As I work on developing a small application, I am contemplating the best strategy for organizing reducers within it. My objective is to retrieve JSON data from the application state and structure it as shown below: { "fruits": [ {"appl ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

Guide to implementing basic authentication within an HTTP request in Angular 4

I'm new to this and I only have experience with the http post method. I need to send the username and password as base authentication for every API request. onSubmit = function(userdata){ this.tokenkey = localStorage.getItem('logintoken&apos ...

Utilizing JSON data from Jade in local JavaScript: A comprehensive guide

Attempting to utilize a JSON object (the entire object, not just a portion) from Node via Jade in my local myScript.js. Here is what my Jade file looks like: span(class="glyphicon glyphicon-pencil" onclick="confirm(\"#{myJSON.taskid}\", \" ...

The horizontal overflow in the HTML code was unsuccessful

I stumbled upon an interesting issue where I applied a div with specific styling: overflow-x: scroll However, the outcome was not as expected. Instead of overflowing, the content simply started on a new line. Here is the source code for reference: & ...