【发布时间】:2019-08-22 11:08:44
【问题描述】:
我有一个日期日历选择器的输入,它将日期存储在服务器上并返回它们onInit。我遇到的问题是当没有存储或选择日期时,它返回 01/01/0001 数字。如果尚未在服务器上选择或保存任何内容,我希望输入为空或具有 dd/mm/yyyy 之类的占位符。所以我构建了一个自定义管道,我无法让它与 ngModel 一起使用。
我收到一个错误,价值未定义。
HTML:
<div class="form-group">
<label for="motDate">MOT Date</label>
<input type="text" class="form-control" placeholder="dd-mm-yyyy" ngbDatepicker #d="ngbDatepicker" (focus)="d.open()" #motDate>
<input type="hidden" [ngModel]="model.motDate | dateNotEmpty" (ngModelChange)="onMOTDateSelected($event)" name="motDate" />
</div>
组件打字稿:
export class VehicleFormComponent implements OnInit {
@ViewChild('motDate') motDatePicker;
ngOnInit() {
// shows the dates from the server in the right format using moment
this.motDatePicker.nativeElement.value = `moment(this.model.motDate).format('DD/MM/YYYY');`
}
onMOTDateSelected(e) {
this.model.motDate = new Date(e.year.toString() + '-' + `e.month.toString() + '-' + e.day.toString());`
}
}
自定义管道:
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateNotEmpty',
pure: false
})
export class DateNotEmptyPipe extends DatePipe implements PipeTransform {
transform(value: any, format: string): any {
if (value.indexOf('0001') > -1) {
return "";
} else {
return new DatePipe('en-GB').transform(value, format);
}
}
}
【问题讨论】:
-
将
if(value.indexOf('0001') > -1) {更改为if(value && value.indexOf('0001') > -1) {有帮助吗? -
这消除了错误并使项目恢复工作,但我仍然看到没有选择日期的 0001 日期。我需要在 typescript onInit() 中使用管道而不是 html 吗?
-
stackoverflow.com/questions/56685403/…,但如果只想使用javascript的对象日期,您可以使用NgbDateAdapter ng-bootstrap.github.io/#/components/datepicker/examples#adapter,进行本地化配置区域设置并注册区域设置数据,如i18n指南中所述:angular.io/guide/i18n
-
我猜不是制作管道,而是在获取值时在 ngOnInit() 中做同样的事情吗?它将检查年份的索引,如果返回'0001',则将其留空。
标签: angular typescript angular7