我在我的angular2應用程序中使用ng2-bootstrap datepicker。我想隱藏點擊外部的日期選擇器彈出窗口。我嘗試了這個question中建議的解決方案。僅在外部點擊時隱藏日期選擇器
但是,在選擇日期或切換到月/年對話框時,它不起作用,它會關閉日期選擇器。
經過調查後發現,這個問題的原因在於單擊時返回的事件目標最初不在元素ref中,但是它是在datepickers組件實現中使用ngIf單擊獲得的。
這是一個plunker解決這個問題。
有什麼建議如何解決這個問題?
我在我的angular2應用程序中使用ng2-bootstrap datepicker。我想隱藏點擊外部的日期選擇器彈出窗口。我嘗試了這個question中建議的解決方案。僅在外部點擊時隱藏日期選擇器
但是,在選擇日期或切換到月/年對話框時,它不起作用,它會關閉日期選擇器。
經過調查後發現,這個問題的原因在於單擊時返回的事件目標最初不在元素ref中,但是它是在datepickers組件實現中使用ngIf單擊獲得的。
這是一個plunker解決這個問題。
有什麼建議如何解決這個問題?
您需要將點擊事件更改爲mousedown。
import {Component, Input, Output, ElementRef} from '@angular/core';
@Component({
selector: 'my-datepicker',
host: {
'(document:mousedown)': 'onClick($event)',
},
template: `
<label>{{label}}</label>
<input [(ngModel)]="dateModel" class="form-control" (focus)="showPopup()" />
<datepicker class="popup" *ngIf="showDatepicker" [(ngModel)]="dateModel" [showWeeks]="true"></datepicker>
`,
styles: [`
.popup {
position: absolute;
background-color: #fff;
border-radius: 3px;
border: 1px solid #ddd;
height: 251px;
}
`],
})
export class DatepickerComponent {
@Input() dateModel: Date;
private showDatepicker: boolean = false;
constructor(private _eref: ElementRef) { }
showPopup() {
this.showDatepicker = true;
}
onClick(event) {
if (!this._eref.nativeElement.contains(event.target)) {
this.showDatepicker = false;
}
}
}
這不能解決我所解決的問題,它在選擇日期時仍隱藏日期選擇器。我希望日期選擇器僅在外部點擊時隱藏。 –
再次檢查,我忘了保存...對不起:P – AMagyar
你可以監聽器連接到窗口上單擊事件。這將捕獲所有點擊。
要防止日期選擇器在點擊它時被關閉,您可以將偵聽器添加到datepicker(或任何不應該關閉datepicker的元素),並在MouseEvent上調用stopPropagation。
constructor(private el: ElementRef) {
this.el.nativeElement.onclick = (ev: MouseEvent) => {
ev.stopPropagation(); //Do not close Datepicker
};
window.addEventListener("click", this.handleClick);
}
handleClick = (ev: MouseEvent) => {
this.showDatepicker = false;
};
ngOnDestroy() { //Do not forget to remove the listener
window.removeEventListener("click", this.handleClick);
}
這是非常快速和簡單的解決方案,我都做了,
在HTML文件中
<div class="input-group">
<input class="form-control" placeholder="yyyy-mm-dd"
name="dp" [(ngModel)]="model" ngbDatepicker [dayTemplate]="customDay" [markDisabled]="isDisabled" #datepicker="ngbDatepicker">
<button class="input-group-addon" (click)="d.toggle()" type="button">
<img src="img/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
</button>
</div>
在component.ts文件
// local reference varible of datepicker input
@Viewchild('datepicker') datepicker;
// listen to document click event and handle closeDponOutsideClick event
@HostListener('document:click', ['$event'])
closeDponOutsideClick(event) {
if (event.target.offsetParent !== null && event.target.offsetParent.tagName !== 'NGB-DATEPICKER') {
this.datepicker.close();
}
}
說明:聽文檔單擊事件和檢查,有針對性偏移父元素不是null,以及它的標籤名稱不等於「NGB-日期選擇器」,因爲日期選擇器之外點擊一下,你總能得到不同的offsetParent名字比'NGB-DATEPICKER'。
希望這可以幫助別人。
你能再次測試嗎?我保存了更改... – AMagyar