在模板上添加一个按钮,点击按钮时打开模态对话框。使用ngModel绑定来获取所选日期。以下是可用的代码示例:
在模板上添加的按钮:
在组件.ts文件中:
import { Component } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-datepicker',
template: '
selectedDate: any;
constructor(private modalService: NgbModal) { }
openDatePicker() {
const modalRef = this.modalService.open(NgbdModalContent);
modalRef.componentInstance.data = { selectedDate: this.selectedDate };
modalRef.result.then((result) => {
if (result !== undefined) {
this.selectedDate = result;
}
}, (reason) => {
console.log(reason);
});
}
}
在模态对话框组件中:
import { Component, Input } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({ selector: 'ngbd-modal-content', templateUrl: './modal-content.component.html' }) export class NgbdModalContent { @Input() data;
constructor(private activeModal: NgbActiveModal) { }
get selectedDate() {
return this.data.selectedDate;
}
set selectedDate(date: any) {
this.data.selectedDate = date;
}
closeModal() {
this.activeModal.close(this.selectedDate);
}
}
在模态对话框组件的HTML模板中: