Wil*_*lyC 0 datepicker angular2-forms ng2-bootstrap angular2-formbuilder angular
我环顾四周,找不到任何确定的方法-您可以将ng2-bootstrap datepicker与Angular2模型驱动的表单一起使用,还是仅适用于模板表单?
该文档介绍了选择器,以便您可以按以下方式使用它(作为示例):
<datepicker [(ngModel)]="startDate" ></datepicker>
Run Code Online (Sandbox Code Playgroud)
...似乎确实有效。理想情况下,我想这样使用它:
<datepicker formControlName="startDate" ></datepicker>
Run Code Online (Sandbox Code Playgroud)
...但似乎开箱即用。有没有办法将此模块与模型驱动的表单一起使用?如果没有,是否存在一种适用于模型驱动表单的合理替代方案?(我也尝试过ng2-datepicker,但是有一个突出的错误使SystemJS难以使用,这很不幸,因为它看起来很光滑)。
我为ng2-bootstrap datepicker创建了一个简单的包装,以将其与ReactiveFormsModule一起使用。它会消耗时间,因此您可以根据需要进行改进。
custom-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() {}
}
Run Code Online (Sandbox Code Playgroud)
组件中的用法
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()
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2974 次 |
| 最近记录: |