Custom directive for input date control cannot read value

Posted by: binhgreensoft on 24 November 2017, 4:14 pm EST

    • Post Options:
    • Link

    Posted 24 November 2017, 4:14 pm EST

    I use wj-input-date in Angular 4 app like bellow:

    Component:

    
      <wj-input-date [(value)]="testDate" [format]="'dd/MM/yyyy'" [isRequired]="false" my-date-input="dd/MM/yyyy"></wj-input-date>
    
    

    Directive

    
    import { Directive, ElementRef, HostListener, OnInit } from '@angular/core';
    
    @Directive({
        selector: '[my-date-input]'
    })
    export class DateInputDirective implements OnInit {
        private dateFormat: string = "dd/MM/yyyy";
    
        constructor(private el: ElementRef) {
        }
    
        ngOnInit(): void {
        }
    
        @HostListener("valueChanged", ["$event"])
        onValueChanged(event: any) {
            console.log(this.el.nativeElement.value); // always return undefined
        }
    
        @Input('my-date-input')
        public set defineInputType(format: string) {
            this.dateFormat = format;
        }
    }
    
    

    Why value read in valueChanged event always return undefined?

    Thanks.

  • Posted 26 November 2017, 10:55 pm EST

    Hi,

    Why value read in valueChanged event always return undefined?

    This is because you are reading the value at incorrect location. WjInputDate is not an HTMLInput element. To get the valid value, use either of the following.

    
      @HostListener("valueChanged", ["$event"])
      onValueChanged(event: any) {
        console.log( this.el.nativeElement['$WJ-CTRL'].value );
        console.log( this.el.nativeElement['$WJ-CTRL'].inputElement.value );
        console.log( this.el.nativeElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].value );
      }
    

    ~nilay

  • Posted 28 November 2017, 7:46 pm EST

    Oh, thank you. I’m just starting with Angular application.

Need extra support?

Upgrade your support plan and get personal unlimited phone support with our customer engagement team

Learn More

Forum Channels