我为 ng2-bootstrap datepicker 制作了简单的包装器,以便将它与 ReactiveFormsModule 一起使用。它使用时刻,因此您可以根据需要对其进行改进。
现场演示
自定义 datepicker.component.ts
import { Component, forwardRef, Provider } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import * as moment from 'moment';
let DATEPICKER_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomDatepickerComponent),
multi: true
};
@Component({
selector: 'custom-datepicker[formControlName]',
template: `
<datepicker [(ngModel)]="datePickerValue"></datepicker>
`,
providers: [DATEPICKER_VALUE_ACCESSOR]
})
export class CustomDatepickerComponent implements ControlValueAccessor {
change = (_: any) => {};
_customDatePickerValue;
_datePickerValue: Date;
get customDatePickerValue() {
return this._customDatepickerValue;
}
set customDatePickerValue(value) {
this._customDatepickerValue = value;
this.change(value);
}
get datePickerValue() {
return this._datePickerValue;
}
set datePickerValue(value) {
this._datePickerValue = value;
this.customDatePickerValue = moment(value).format('DD/MM/YYYY');
}
writeValue() {}
registerOnChange(fn) {
this.change = fn;
}
registerOnTouched() {}
}
在您的组件中使用
app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
template: `
<form [formGroup]="form">
<custom-datepicker formControlName="customDatepickerValue"></custom-datepicker>
</form>
<pre>{{form.value | json }}</pre>
`
})
export class AppComponent {
form: FormGroup = new FormGroup({
customDatepickerValue: new FormControl()
})
}