Disabling Autocomplete on Angular Date Picker Directive

Recently, I inherited a JQuery Date picker directive that adds date pickers to input HTML controls. As a newcomer to Angular, I have been struggling with modifying this functionality created by a previous developer.

I am specifically looking for a way to disable the auto-complete feature on all the date pickers that are generated through this directive. Is there a solution to achieve this?

export class DanialDatePickerDirective implements ControlValueAccessor {

    constructor(protected el: ElementRef, private renderer: Renderer) { }

    @Input() dateformat: string = "DD-MMM-YY";
    @Input() ngModel: any;
    @Input() setDefaultDate: boolean;
    onModelChange: Function = () => { };
    onModelTouched: Function = () => { };

    writeValue(value: any) {
        if (value) {
            var ff = new Date(value);
            $(this.el.nativeElement).datepicker("setDate", ff);
        }
        else {
            $(this.el.nativeElement).datepicker("setDate", "");
        }
    }

    registerOnChange(fn: Function): void {
        this.onModelChange = fn;
    }

    registerOnTouched(fn: Function): void {
        this.onModelTouched = fn;
    }

    onBlur() {
        this.onModelTouched();
    }

    ngAfterViewInit() {
        var self = this;
        $(this.el.nativeElement).datepicker({
            dateFormat: 'dd-M-y',
            changeMonth: true,
            changeYear: true,
            showOtherMonths: true,
            selectOtherMonths: true
        });

        if (this.setDefaultDate) {
            var ff = new Date(self.ngModel);
            setTimeout(function () {
                $(self.el.nativeElement).datepicker("setDate", ff);
            }, 200);
        }

        $(this.el.nativeElement).on('change', (e: any) => {
            var model = e.target.value;
            var date = null;
            var monthstring = '';
            if (model.indexOf("-") > 0){
                monthstring = model.substring(model.indexOf("-") + 1, 5);
            }

            if (isNaN(parseInt(monthstring))) { 
                var tt = moment(model, "DD-MMM-YY").format('YYYY-MM-DD'); 
                date = tt;
                model = moment(model, "DD-MMM-YYYY").format('MM-DD-YYYY') 
            }
            else {

                date = moment(model, "DD-MM-YYYY").format('YYYY-MM-DD'); 
                model = moment(model, "DD-MM-YYYY").format('MM-DD-YYYY') 
            }

            $(".ui-datepicker a").removeAttr("href"); 
            self.onModelChange(date);

             self.writeValue(date.toString());
        });
    }

}

Answer №1

A method that has proven effective for me is as follows:

Firstly, ensure to include autocomplete="off" in both the input element itself and its parent form.

Secondly, always give your input field a unique name. One way to accomplish this is by generating a random number and using it as part of the field's name.

  private getUniqueName() {
    return Math.floor(Math.random() * Date.now());
  }

Explanation:

In the past, adding autocomplete="off" to form fields was common practice to disable browser autocomplete functionality. While Chrome still recognizes this attribute for autocomplete data, it may not work for autofill data. https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill.

Therefore, while autocomplete="off" helps with autocomplete issues, tricking the browser by constantly changing the input name will prevent autofill from interfering ;)

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

Dramatist - shutting down an angular pop-up dialog

I am currently utilizing the Playwright tool to carry out testing on an angular application. One particular scenario involves a modal that is displayed by default when a page is loaded. Despite my best efforts, I have been unable to successfully close this ...

What is the best way to utilize moment.js for adding days while excluding weekends?

I have a requirement to set a default follow-up date that is two days ahead of the current date. The existing code for this functionality is as follows: const Notify = moment().add(2, 'days').toDate(); Now, I need to modify this code to exclude ...

Guide on implementing an onClick event for rows in an Angular Mat-Table and navigating to a separate page

I'm seeking guidance on how to implement a click event for a specific row that will navigate to the next form while carrying over the values of the clicked row. I find this concept a bit perplexing at the moment. <!-- Position C ...

Angular 4 router is being implemented for drag and drop functionality by ng-dragula with the

Our app is built with angular 4 and we are currently attempting to customize our theme using dragula. I successfully implemented all aspects of the page and everything seems to be working properly, including persistence. However, there is one major issue t ...

Using Angular UI TinyMCE to import a Word file

Can I import a local word document into the text area generated by the Angular UI TinyMCE directive? ...

How Can I Build a Dynamic Field Form Builder in Angular 4?

While working with dynamic JSON data, I needed to create fields dynamically. For instance, if my JSON array contains 3 values, I would generate 3 input checkboxes dynamically as shown below: <ng-template ngFor let-numberOfRow [ngForOf]="numberOfRows"&g ...

Using ngModel conditionally in Angular 2

I am facing a requirement where I need to bind a phone number to ngModel only if it is present. The code I am using is as below: <cd-input size="15" [(ngModel)]="phone_numbers[0].full_number" [reformat]="something" [format]="something" placeh ...

Updating the Nuxt3 editing page with useFetch and $fetch for fetching data, along with a typed storage object that prevents loading issues

My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in cod ...

How can I delay the ng-show element until the ng-hide CSS transition has finished?

Looking for a simple solution to my implementation issues. I'm faced with the following DOM setup: <h1 class="fade" ng-repeat="child in parent.children" ng-show="parent.activeChild == child">@{{ child.title }}</h1> How can I smoothly fad ...

Choosing Vue select options depending on a condition

I am working on a dropdown template with Vue.js and have encountered some challenges. Here is the basic structure of my dropdown: <select v-model="selectedClient" class="stat-select text-u-c"> <option disabled value="">Please select a Client ...

Setting a default time on a p-calendar: A step-by-step guide

I am currently using the following p-calendar component in my webpage: <p-calendar [style]="{'width':'100%'}" [inputStyle]="{'width':'100%'}" dateFormat="dd-mm-yy" [fo ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

Issue encountered while initializing a fresh project with Angular CLI version 13.1.0

I encountered an issue while trying to create a new project with Angular CLI v13.1.0 \ Installing packages (npm)...npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

Dynamic labeling of breadcrumbs in Angular is the way to go!

I am aiming to develop a breadcrumb navigation system with one element that changes dynamically. Here's an example: Home > Category A > Subcategory 1 > XYZ The categories "Category A" and "Subcategory 1" remain constant, while "XYZ" varies ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

AngularJs is being used to extract data from Firebase with the help of $value, $id, and

I have been working on retrieving data from Firebase in my HTML using AngularJS. Everything is functioning well, however, when I access the child node, the data is displayed in an unexpected format. Please refer to the images below for more details: This ...

reposition md-dialog labels on the fly

My tab dialog is not evenly arranged as shown below: https://i.sstatic.net/ghn4v.jpg Despite trying the flex directive, the tabs ("DESCRIPTION, MEANS,...) do not span the available space uniformly. Here is a shortened version of my HTML: <md-t ...

Guide to configuring global providers in Angular2 version 2.0.0 RC.5

What is the process for setting up global providers when utilizing a new feature called NgModule? In previous instances, I could accomplish this with the following code: bootstrap(AppComponent, [ GlobalServiceAAA, GLOBAL_PROVIDERS_BBB ]); When usin ...

Importing mock data into an AngularJS unit test

Having some trouble setting up my AngularJS application for testing controllers, routes, templates, and more. I'm running into difficulties getting the helper methods from angular-mocks.js to function properly, especially module and inject. I am usin ...

Tips on sending a list via @Input using Angular5

I was seeking guidance on how to pass a list through an input. In my parent component, I have the following: list: Hero[] = [{Id: 2, Name: "Sll"}, {Id: 3, Name: "Sldsadasd"}] and in the HTML: <app-add-hero list="{{list}}" hero={{hero}}></app-ad ...