gerl
gerl

Reputation: 1181

angular2 bootstrap datepicker

I'm trying to figure out how to hide the angular2 bootstrap date picker when I blur out of the input field. There is no event as (blur) for angular and typescript. Ive tried using d2.toggle() but it doesnt work.

 <input class="form-control" placeholder="yyyy-mm-dd"
         name="dp" placement="bottom-right" [(ngModel)]="model2" ngbDatepicker 
         #d2="ngbDatepicker" (click)="d2.open()" >

Here is a plunker

Upvotes: 1

Views: 1304

Answers (3)

Vega
Vega

Reputation: 28711

To make it work with two datepickers, you can wrap the both and set the directive on the wrapper. Then control openings/closings with a flag:

HTML:

<div (clickOutside) = "open === 1 ? d.toggle() : open ===2 ? d2.toggle() : null; open =0">

  <input type="text" class="form-control" id="email" name="email" 

  placeholder="From:" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker"
  (click)="open === 2 ? d2.toggle() : null; d.toggle();open = 1" required><br />


   <input type="text" class="form-control" id="toDate" name="toDate" 
  placeholder="To:" [(ngModel)]="toDate" ngbDatepicker #d2="ngbDatepicker"
  (click)="open === 1 ? d.toggle() : null; d2.toggle();open = 2" required>
</div>
</form>

DEMO

Upvotes: 0

Vega
Vega

Reputation: 28711

Write a directive which will listen to the clicks on outside of the datepicker. The main point is to check whenever the DOM element, that receives the click, is the one which has the directive on it.

Directive:

@Directive({
    selector: '[clickOutside]'
})
export class ClickOutsideDirective {
    constructor(private elementRef: ElementRef) {
    }

    @Output()
    clickOutside = new EventEmitter<Event>();

    @HostListener('document:click', ['$event', '$event.target'])
    onClick(event: MouseEvent, targetElement: HTMLElement): void {
        if (!targetElement) {
            return;
        }

        const clickedInside = this.elementRef.nativeElement.contains(targetElement);
        if (!clickedInside) {
            this.clickOutside.emit(event);
        }
    }
}

And add it like so:

HTML:

   <input (clickOutside)="d2.toggle()" class="form-control" placeholder="yyyy-mm-dd"
         name="dp" placement="bottom-right" [(ngModel)]="model2" ngbDatepicker 
         #d2="ngbDatepicker" (click)="d2.toggle()" >

DEMO

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86730

You can simply call Blur method in angular like this

<input class="form-control" placeholder="yyyy-mm-dd"
             name="dp" placement="bottom-right" [(ngModel)]="model2" ngbDatepicker 
             #d2="ngbDatepicker" (blur)="onBlurMethod()" (click)="d2.toggle()" >

and then do whatever you want to do in that method.

Upvotes: 0

Related Questions