ReactiveFormsModuleでng2-bootstrap datepicker用の単純なラッパーを作成しました。それは瞬間を使用するので、あなたのニーズに合わせて改善することができます。
Live demo
カスタム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()
})
}
最初の例を使用するとどうなりますか?エラーが出ていますか?私はこのライブラリを使ったことはありませんが、ngModelとテンプレートフォームでは、 'name'属性が必要です。 –
' name'属性は必要ありません。 ...テンプレート駆動フォームを使用していた場合は、すべて設定されますが、モデル駆動フォームが優先されます。 – WillyC
ご迷惑をおかけして申し訳ありません。第2の例ではなく、第1の例を使用しようとしていたときにそれを読んでいます。 Ooops :-D –