Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 access ngModel variable from a directive

I am trying to build a datetime picker directive like the following.
<input [(ngModel)]="date1" datetime-picker date-only />

and date1 is assigned as a Date, e.g., new Date()

When I display this in html, text in input element looks like the following
Thu Jan 01 2015 00:00:00 GMT-0500

I want to display like the following instead
2015-01-01 00:00:00

I want to format date WITHIN a directive using DatePipe instead of showing result from default toString() function.

My question is; "within a directive, how do I access ngModel variable?", e.g., date1, so that I can add toString() method.

If my approach is not right, please advise me.

like image 254
allenhwkim Avatar asked May 23 '16 02:05

allenhwkim


People also ask

Is ngModel attribute directive?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

What does [( ngModel )] do?

ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.

How do I update my ngModel value?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.


1 Answers

Here is simple and easy way to listen and notify ngModel. I have just demonstrated with jQuery for easy understanding. Practically, it can be anything.

import { Directive, ElementRef } from '@angular/core';
import { NgModel } from '@angular/forms';

@Directive({
    selector: `[ngModel][customDir]`,
    providers: [NgModel]
})
export class CustomDirective {


    constructor(private element: ElementRef, private ngModel: NgModel) {

    }

    ngOnInit() {
        let that = this;
        /* Here you can write custom initialization code */

        /* Listening to the value of ngModel */
        that.ngModel.valueChanges.subscribe(function (value) {
            /* Set any value of your custom control */
            $(that.element.nativeElement).data("newValue",value);
        });

        /* Inform ng model for any new change happened */
        $(that.element.nativeElement).bind("customEvent",function (someNewValue) {
                that.ngModel.update.emit(someNewValue);
            }
        });
    }
}
like image 132
Dhrumil Bhankhar Avatar answered Oct 03 '22 14:10

Dhrumil Bhankhar