nco*_*hen 15 ng-bootstrap angular
我在我的Angular 2 webapp中使用了反应形式,我遇到了将日期分配给ngbDatepicker(ngbootstrap 1 alpha 6)的麻烦.我的对象有一个日期对象,例如:
var myObject = {date: new Date(1, 9, 2016)};
Run Code Online (Sandbox Code Playgroud)
在我的反应形式中,它配置如下:
input.form-control(name='date', ngbDatepicker, #date="ngbDatepicker", placeholder='jj.mm.aaaa', formControlName='date', type="text")
Run Code Online (Sandbox Code Playgroud)
我修补这样的形式:
this.form.patchValue({myObject: myObject});
Run Code Online (Sandbox Code Playgroud)
问题是ngbDatepicker采用以下结构的日期:
{day: DD, month: MM, year: YYYY}
Run Code Online (Sandbox Code Playgroud)
我找到了一个解决方法:
this.form.controls.myObject.controls.date.valueChanges
.map((value) => {
if(value) {
if (typeof value.getMonth === 'function') {
this.form.controls.myObject.patchValue({
date: {
day: value.getUTCDay(),
month: value.getUTCMonth(),
year: value.getUTCFullYear()
}
});
}
}
return value;
})
.subscribe((value) => {
});
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作(每当表单被修补时日期都会更新)但是它太冗长(18行代码)而且我的表单有十几个日期!
所以我的问题是,我可以通过更短的解决方案获得相同的结果吗?
小智 9
我不知道它是否对你有帮助
ng-bootstrap: 1
angular: 2
bootstrap: 4
ngOnInit() {
const now = new Date();
const since = moment().subtract(14,'d').toDate();
this.model.fechaHasta = {year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate()};
this.model.fechaDesde = {year: since.getFullYear(), month: since.getMonth() + 1, day: since.getDate()};
}
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="input-group">
<input class="form-control" placeholder="yyyy-mm-dd"
name="fechaHasta" [(ngModel)]="model.fechaHasta" ngbDatepicker #d10="ngbDatepicker">
<div class="input-group-addon" (click)="d10.toggle()">
<img src="../../shared/img/calendar-icon.png" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
@ncohen,我们也填补了痛苦,请参阅:https ://github.com/ng-bootstrap/ng-bootstrap/issues/754 。目前还没有完美的解决方案,最终的解决方案需要来自 Angular 本身,以 AngularJS 中已知的解析器/格式化程序的形式出现。Angular 存储库中已经有 2 个问题将您的用例作为功能请求进行跟踪:
我相信,目前您最好的选择是将详细代码提取到实用函数中,并在需要转换时调用它(如评论之一所建议)。
| 归档时间: |
|
| 查看次数: |
15800 次 |
| 最近记录: |