angular7 - 如何在 Ionic 4/Angular7 中以反应形式使用logisticinfotech/ionic4-datepicker?
问题描述
我是 Ionic 和 Angular 的新手。我有一个带有日期字段的反应式表单(ReactiveFormsModule)。我正在尝试使用创建的 ionic4-datepicker 组件来替代 ionic-datetime 元素。在阅读了他们的博客(https://www.logisticinfotech.com/blog/ionic4-datepicker-component/)后,我仍然无法在日期字段中获取和设置选定的日期。任何帮助表示赞赏。谢谢。
2019 年 9 月 17 日更新:
不知道发生了什么,但在我从头开始再次创建表单并清除浏览器缓存后,日期选择器工作。我还没有弄清楚如何触发对 myFunction() 的函数调用。这没什么大不了的,因为我不需要执行任何验证或业务逻辑,但很高兴知道。
这是工作代码。享受。
创建-form.page.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-create-form',
templateUrl: './create-form.page.html',
styleUrls: ['./create-form.page.scss'],
})
export class CreateFormPage implements OnInit {
submitted = false;
createForm: FormGroup;
datePickerObjDefaultSettings: any = {}
datePickerObjCustomSettings: any = {
inputDate: new Date(),
fromDate: null,
toDate: null,
showTodayButton: true,
closeOnSelect: true,
disableWeekDays: [0],
mondayFirst: true,
setLabel: 'Set',
todayLabel: 'Today',
closeLabel: 'Close',
disabledDates: [],
titleLabel: 'Select a Date',
monthsList: ["Jan", "Feb", "March", "April", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"],
weeksList: ["S", "M", "T", "W", "T", "F", "S"],
dateFormat: 'YYYY-MM-DD',
clearButton: true,
momentLocale: 'en-US',
yearInAscending: true,
btnCloseSetInReverse: true,
btnProperties: {
expand: 'block',
fill: '',
size: '',
disabled: '',
strong: '',
color: ''
},
highlightedDates: []
};
validation_messages = {
'name': [
{ type: 'required', message: 'Name is required.' },
{ type: 'minlength', message: 'Name must be at least 3 characters long.' },
{ type: 'maxlength', message: 'Name cannot be more than 100 characters long.' },
]
}
constructor(private router: Router, private formBuilder: FormBuilder) { }
ngOnInit() {
this.createForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(100)]],
fromDate: [''],
toDate: [''],
});
}
onSubmit(value: any): void {
this.submitted = true;
if (this.createForm.invalid) {
return;
}
this.router.navigateByUrl('/home');
}
onReset() {
this.submitted = false;
this.createForm.reset();
}
// Either there is a typo in the third-party documentation or bug in the plugin.
// This function is NOT invoked.
myFunction() {
console.log("===> myFunction: ");
}
}
创建-form.html
<ion-content>
<form [formGroup]="createForm" (ngSubmit)="onSubmit(createForm.value)">
<ion-item>
<ion-label position="floating" color="primary">Name</ion-label>
<ion-input type="text" formControlName="name"></ion-input>
</ion-item>
<div>
<ng-container *ngFor="let validation of validation_messages.name">
<div class="error-message"
*ngIf="createForm.get('name').hasError(validation.type) && (createForm.get('name').dirty || createForm.get('name').touched)">
<ion-icon name="information-circle-outline"></ion-icon> {{ validation.message }}
</div>
</ng-container>
</div>
<ion-item>
<ion-label position="floating">From Date</ion-label>
<ion-input readonly formControlName="fromDate" [liIonic4Datepicker]="datePickerObjDefaultSettings" (ionchange)="myFunction()"></ion-input>
<!-- <ion-datetime displayFormat="MMM DD, YYYY" min="2017-01-01"></ion-datetime> -->
</ion-item>
<ion-item>
<ion-label position="floating">To Date</ion-label>
<ion-input readonly formControlName="toDate" [liIonic4Datepicker]="datePickerObjCustomSettings" (ionchange)="myFunction()"></ion-input>
<!-- <ion-datetime displayFormat="MM/DD/YYYY" min="2017-01-01"></ion-datetime> -->
</ion-item>
<ion-grid>
<ion-row>
<ion-col>
<ion-button expand="block" size="medium" type="submit" [disabled]="!createForm.valid">Create</ion-button>
</ion-col>
<ion-col>
<ion-button expand="block" size="medium" type="reset" (click)="onReset()">Reset</ion-button>
</ion-col>
</ion-row>
</ion-grid>
</form>
</ion-content>
创建-form.scss
.error-message {
color: red;
font-size: 14px;
margin: 10px;
}
解决方案
实际上,liIonic4Datepicker 有自己的日期类型是正常的。如果要将默认日期设置为 datepicker,则需要编写将 UTC 日期转换为 datepicker 格式日期的 util 函数。然后将结果修补到表单中(在 OnInit 方法中)。像那样:
convertDate(UTCdate: Date) {
return .....
}
ngOnInit() {
this.myForm.patch({myDate: convertDate('YOUR_DATE')})
// or
this.myForm.controls.myDate.setValue(convertDate('YOUR_DATE'))
}
如果你想提交表单,你应该做同样的事情来将 datepicker 日期转换为正常日期。
submitForm {
const { myDate } = this.myForm.value;
convertedDate = convertToUTC(myDate);
this.api.submit(convertedDate)
}
推荐阅读
- java - 如何检查文件是否为图像
- python - Python Asyncio queue get 没有收到消息
- java - 应该首选哪个集合来处理、存储和迭代使用 selenium webdriver 的大量窗口弹出窗口?
- python - PyOpenGL:glutTimerFunc 回调缺少必需的参数“值”
- javascript - 到达 CSS 断点时触发事件
- javascript - 我可以使用 jQuery 独立定位 CSS 类的实例吗?
- java - 如何在java代码中连接后检查oracle数据库版本
- rest - Adobe sign API - create a widget with pre-filling details
- rest - What HTTP status code should a Web API return after successful completion, if it performed both UPDATES and INSERTS?
- javascript - Update highstock chart dynamically