Không có bộ chọn DateTime cho Angular 7?
Tôi không thể tìm thấy bất kỳ bộ chọn DateTime nào cho Angular 7. Vì vậy, tôi quyết định kết hợp Bộ chọn ngày và Bộ chọn thời gian
https://ng-bootstrap.github.io/#/components/datepicker
https://ng-bootstrap.github.io/#/components/timepicker
<ng-template #dateTimePicker>
<ngb-datepicker #createdStartDate name="datepicker"></ngb-datepicker>
<ngb-timepicker #createdStartTime name="timepicker" [meridian]="true"></ngb-timepicker>
</ng-template>
<form [formGroup]="managePromotionsForm"
<div class="col-md-6">
<div class="row form-group">
<label class="col-md-4 control-label" for="createdStartDate" translate="">Created From </label>
<div class="col-md-6">
<div class="input-group">
<input readOnly class="form-control" id="createdStartDate" placeholder="From Date"
[formControl]="controls['createdStartDate']">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" [ngbPopover]="dateTimePicker" type="button"></button>
</div>
</div>
</div>
</div>
</div>
</form>
Đây là những gì tôi có cho đến nay
Bây giờ làm thế nào để hiển thị ngày và giờ đã chọn trên createdStartDatehộp văn bản?
Trả lời
Nếu muốn, bạn có thể sử dụng kết hợp ngbDropDown, ngbDatePicker và ngbTimePicker
Đối với điều này, bạn cần hai biến và một getter
date: any;
time:any= {hour:0,minute:0};
_value;
label;
ngOnInit()
{
this.getDatetime()
}
getDatetime() {
let value = null;
if (!this.date) {
if (!this.time) value = "yyyy/MM/dd hh:mm";
else
value =
"yyyy/MM/dd " +
("0" + this.time.hour).slice(-2) +
":" +
("0" + this.time.minute).slice(-2);
}
if (!value) {
value = new Date(Date.UTC(
this.date.year,
this.date.month - 1,
this.date.day,
this.time ? this.time.hour : 0,
this.time ? this.time.minute : 0
);
this._value=value;
} else
this._value=null
this.form.get("control").setValue(this._value);
this.label=value;
}
<form [formGroup]="form">
<div ngbDropdown>
<button class="datepicker btn btn-link" ngbDropdownToggle>{{_value?(_value|date:'medium'):label}}</button>
<div ngbDropdownMenu >
<ngb-datepicker #dp [(ngModel)]="date" (dateSelect)="getDatetime()"[ngModelOptions]="{standalone:true}" ></ngb-datepicker>
<ngb-timepicker [ngModel]="time" (ngModelChange)="time=$event;getDatetime()"[ngModelOptions]="{standalone:true}"></ngb-timepicker>
</div>
</div>
<button class="btn btn-primary">submit</button>
Xem trong stackblitz
LƯU Ý: Đây là trường hợp mà chúng tôi sẽ tạo một điều khiển biểu mẫu tùy chỉnh để không tạo ra sự phụ thuộc
Cập nhật cho tò mò, trong stackblitz, tôi thực hiện điều khiển biểu mẫu tùy chỉnh
Nếu bạn muốn tạo một phần tử biểu mẫu mà bạn có thể liên kết. Cách tốt hơn là tạo một thành phần riêng biệt và triển khai trình truy cập giá trị điều khiển .
Sau đó, bạn có thể sử dụng thành phần như một phần tử biểu mẫu và liên kết ngModal hoặc điều khiển biểu mẫu với nó.