Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround?

Here is the HTML:

<div class="md-menu-demo menudemoBasicUsage" ng-controller="BasicDemoCtrl as ctrl" ng-app="MyApp">

  <div class="menu-demo-container" layout-align="center center" layout="column">
    <h2 class="md-title">Month Select</h2>
    <p>Select a month by clicking the input</p>
    <md-menu>

      <input md-menu-origin="" aria-label="Open phone interactions menu" ng-focus="ctrl.openMenu($mdOpenMenu, $event)" ng-model="ctrl.selectedMonth">
      <md-menu-content width="4" ng-click="$event.stopPropagation()">
<md-datepicker ng-model="dateFilter" md-placeholder="Till date" md-min-date="dateFilter.fromDate"></md-datepicker>
      </md-menu-content>
    </md-menu>
  </div>
</div>

And here is the JS:

angular
  .module('MyApp')
  .controller('BasicDemoCtrl', function DemoCtrl($mdDialog) {
    var originatorEv;

    this.openMenu = function($mdOpenMenu, ev) {
      originatorEv = ev;

          $mdOpenMenu(ev);
        };

        this.setMonth = function(val) {
          this.month = val;
          this.setSelectedMonth();
        };

        this.notificationsEnabled = true;
        this.toggleNotifications = function() {
          this.notificationsEnabled = !this.notificationsEnabled;
        };

        this.nextYear = function() {
          this.year++;
          this.setSelectedMonth();

        };

        this.preYear = function() {
          this.year = this.year - 1;
          this.setSelectedMonth();
        };
        
}).directive('stopEvent', function() {
        return {
          restrict: 'A',
          link: function(scope, element, attr) {
            if (attr && attr.stopEvent)
              element.bind(attr.stopEvent, function(e) {
                e.stopPropagation();
              });
          }
        };
      });

Answer №1

I managed to come up with a working solution, although it may not be the most optimal.

HTML:
<md-datepicker id="myDatePicker"
    ng-model="dateFilter" 
    md-placeholder="Till date" 
    md-min-date="dateFilter.fromDate">
</md-datepicker>

JS:
function setupDateButton()
{
    var dateButtonFix = document.getElementById("myDatePicker").children;
    for (var i = 0; i < dateButtonFix.length; i++)
    {
        if (dateButtonFix[i].tagName == 'BUTTON' || dateButtonFix[i].tagName == 'DIV')
        {
            if (dateButtonFix[i].tagName == 'DIV')
            {
                var child2 = dateButtonFix[i].children;
                for (var j = 0; j < child2.length; j++)
                {                               
                    if (child2[j].tagName == 'BUTTON')
                    {
                        child2[1].setAttribute("md-prevent-menu-close", "md-prevent-menu-close");
                    }
                }
             }
             else
                 dateButtonFix[0].setAttribute("md-prevent-menu-close", "md-prevent-menu-close");
         }
    }    
}    
setupDateButton();

There must be a more efficient way to achieve this functionality, but for now, it gets the job done.

Answer №2

Recently, I encountered the same issue and developed a specialized directive to address it.

Below is the code for my custom directive:

const TRUE = 'true';
const PREVENT_CLOSE = 'md-prevent-menu-close';

class CalendarBtnFixDirective {
  constructor() {
    this.restrict = 'C';
    this.require = '^^mdDatepicker'
  }

  link(scope, element, attrs, datePickerCtrl) {
    const nativeElement = element[0];
    const preventMenuClose = datePickerCtrl.$attrs.mdPreventMenuClose;

    if ([TRUE, PREVENT_CLOSE].indexOf(preventMenuClose) !== -1) {
      nativeElement.setAttribute(PREVENT_CLOSE, PREVENT_CLOSE);
    }
  }
}

export const MdCalendarFixModule = angular
  .module('md.calendar.fix.module', [])
  .directive('mdDatepickerTriangleButton', () => new CalendarBtnFixDirective())
  .name;

You can now utilize the md-prevent-menu-close attribute in your md-datepicker

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

Executing a service prior to the loading of Angular 7 applications or components

Currently, I am in the process of developing an application using Angular 7. So far, everything is running smoothly as I have successfully managed API calls, JWT Token authentication with C#, and updating LocalStorage when needed during user login and logo ...

What is the method with the greatest specificity for applying styles: CSS or JS?

When writing code like the example below: document.querySelector('input[type=text]').addEventListener('focus', function() { document.querySelector('#deletebutton').style.display = 'none' }) input[type=text]:focu ...

Can you explain what JSX is, its purpose, and the benefits of using it?

As I delve into the world of React, I can't escape the constant mention of JSX. Despite my efforts to grasp it by watching tutorials, the concept still eludes me. Even after consulting the documentation, my mind remains in a state of confusion. To m ...

Discover the process of utilizing doc.getElementbyClassName to determine if any of its elements are blank

On my HTML invoice table, I sometimes have empty elements that cause the row to misalign. To fix this, I want to add whitespace if an element is empty. Here is the structure of the table: <div class="invoiceTable"> <div class="titles2" style=" ...

Determining the class condition using AngularJS ng-class

I am working with an HTML element that contains AngularJS directives: <div class="progress"> <span ng-repeat="timeRangeObject in timeRangeObjects" style="width: {{timeRangeObject.percentage}}%" ...

Tips for preventing directly mutating a prop within a recursive component

The child operates on its own copy of the prop data and can notify the parent using `$emit` when a change occurs. Imagine dealing with a recursive tree structure, like a file system for example: [ { type: 'dir', name: 'music', childr ...

Ways to make the input field appear invalid without the use of forms, causing the bottom outline to turn red when a specific condition is met

Currently, the application does not utilize any forms. I am interested in making the input field invalid under certain conditions within the component. For example, if a user leaves the input field blank, I would like the bottom outline to turn red when an ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

Ways to display or conceal text using Vanilla JavaScript

I am struggling to toggle text visibility using Vanilla JS. Currently, I can only hide the text but cannot figure out how to show it again. <button id="button">my button</button> <div> <p id="text">Hello</p& ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

React - The `component` prop you have supplied to ButtonBase is not valid. Please ensure that the children prop is properly displayed within this customized component

I am attempting to use custom SVG icons in place of the default icons from Material UI's Pagination component (V4). However, I keep encountering this console error: Material-UI: The component prop provided to ButtonBase is invalid. Please ensure tha ...

Unexpected database query result in Node.js

In my newuser.js file for a node.js environment with a mongodb database managed through mongoose, I have the following code: //newuser.js //This code is responsible for creating new user documents in the database and requires a GET parameter along with a ...

Adding points to a bar or pie chart in a Vue environment can be achieved dynamically by utilizing Vue's reactivity system

Looking to bootstrap a Highcharts bar chart and dynamically add points to it within a Vue container, the documentation references addPoint(), setData(), and update(). However, I struggled to make any of these methods work. The provided demo for updating a ...

Sync Data Automatically from SQL Database

For the past two months, I've been researching how to achieve an effect similar to the auto-updating sales on the page. So far, I haven't had any luck. I do have a PHP file that counts the number of results in a database and displays them as a n ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

Determine if a radio button is selected using Jquery

I am currently working on a script that should uncheck a radio button if it is checked, and vice versa. However, I'm facing an issue where the script always registers the radio button as checked even when it's not. Below is the code snippet in q ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

Trigger the onclick method by selecting an icon within the MUI DataGrid

Currently, I am utilizing the default MUI Dialog model in the "DialogModel.js" component. Additionally, I have integrated another MUI DataGrid component as shown below: // RulesTable.js import * as React from 'react'; import { DataGrid } from &a ...