[英]Angular 7+ Using CustomPipe on ngModel
我有一個帶有日期日歷選擇器的輸入,該輸入將日期存儲在服務器上並在onInit
上返回它們。 我遇到的問題是,當日期沒有存儲或選擇時,它返回01/01/0001數字。 我希望輸入為空,或者如果服務器上未選擇任何內容或將其保存,則有一個占位符,如dd / mm / yyyy。 因此,我建立了一個自定義管道,使其無法與ngModel
一起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);
}
}
}
我認為這會起作用。
這是您的代碼:
//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>
//typescript
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());`
}
}
//custom pipe
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 {
console.log('Value here': value);
if (value && value.indexOf('0001') > -1) {
return "";
} else {
return new DatePipe('en-GB').transform(value, format);
}
}
}
感謝您在上面的評論中讓Sunny睜開眼睛,我已經將此管子在一些地方使用過,因此想在這里重復使用它,並且無緣無故地卡住了。 在日期初始化之后,我現在添加了一個if語句,它可以正常工作:
也感謝其他人在旅途中為我提供的幫助,非常感謝!
this.motDatePicker.nativeElement.value = moment(this.model.motDate).format('DD/MM/YYYY');
if (this.motDatePicker.nativeElement.value.indexOf('0001') > -1) {
this.motDatePicker.nativeElement.value = "";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.