我正在使用bootstrap4 datepicker https://ng-bootstrap.github.io/#/components/datepicker
我想在日历外单击时关闭datepicker
。现在,当用户选择日期时,它将关闭。
我的HTML
文件代码如下:
<input ngbDatepicker #d="ngbDatepicker" (click)="d.toggle();" [formControl]="eventForm.controls['event_date']" value="12/03/2017" type="text" [readonly]="true" autocomplete="off">
我尝试在body标签中添加(click)="d.close();"
。但是,当我尝试从日历中更改月份和年份时,它也很接近
当用户点击日历外部时,我必须在HTML
或component
中关闭此datepicker
进行哪些更改?
答案 0 :(得分:4)
是的,我遇到了同样的问题...这对我来说很有效:
组件HTML:
<input placeholder="{{ task.deadline.year }}-{{ task.deadline.month }}-{{ task.deadline.day }}" name="date" id="date" [(ngModel)]="task.deadline" ngbDatepicker #d="ngbDatepicker" (click)="!completed && d.toggle(); $event.stopPropagation();" (document:click)="closeFix($event, d)" readonly>
和TS(您唯一需要的是closeFix()函数):
closeFix(event, datePicker) {
if(event.target.offsetParent == null)
datePicker.close();
else if(event.target.offsetParent.nodeName != "NGB-DATEPICKER")
datePicker.close();
}
答案 1 :(得分:0)
当用户离开div
时,您可以使用on-mouseleave事件关闭日期选择器<input on-mouseleave="d.close()" ngbDatepicker #d="ngbDatepicker" (click)="d.toggle();" [formControl]="eventForm.controls['event_date']" value="12/03/2017" type="text" [readonly]="true" autocomplete="off">
度过美好的一天!
答案 2 :(得分:0)
在你的component.ts中,
import { ViewChild } from '@angular/core';
@Component({
host: {
'(document:click)': 'closeDatepicker($event)',
}
})
export class MyComponent {
@ViewChild('d') eventDate;
closeDatepicker(e) {
if (!this.eventDate.isOpen() || (e.target.id === 'd' && e.target.id === 'dropdown-icon')
|| (e.target.offsetParent && e.target.offsetParent.localName.includes('ngb-datepicker'))
|| !(e.target.parentElement && e.target.parentElement.parentElement &&
!e.target.parentElement.parentElement.localName.includes('ngb-datepicker'))) {
return;
}
if (this.eventDate.isOpen() && e.target.id !== 'd' && e.target.id !== 'dropdown-icon') {
this.eventDate.close();
}
}
}
答案 3 :(得分:0)
这似乎是一个老问题,但也想与我分享解决方案。我们遇到了同样的问题,但是我们使用的是Angular Web Element,我们必须深入研究DOM元素才能找到 NGB-DATEPICKER 标记名。下面是HTML文件和打字稿代码
HTML
<button class="btn btn-outline-secondary calendar" (click)="yed.toggle();ysd.close();$event.stopPropagation();"
(document:click)="closeFix($event, yed)" type="button">
<i class="fa fa-calendar" aria-hidden="true"></i>
</button>
TYPESCRIPT
closeFix(event, datePicker) {
if(event.target.offsetParent == null)
datePicker.close();
else if(this.clickedInNgbDatePicker(event.path))
datePicker.close();
}
clickedInNgbDatePicker(eventPath){
let datePickerClicked = true;
eventPath.forEach(function(item){
datePickerClicked = (item.tagName != "NGB-DATEPICKER" && datePickerClicked)
});
return datePickerClicked;
}
答案 4 :(得分:0)
从3.0.0版开始,此问题已通过[autoclose]="'outside'"
<input type="text" ngbDatepicker #d="ngbDatepicker" [autoclose]="'outside'"/>