【发布时间】:2021-03-08 19:07:33
【问题描述】:
我正在尝试以角度反应形式使用 ngbDatepicker,并且希望能够显示初始值。
我的问题是very similar to another one 有一个关键的区别,我也在使用formly,这是一个用于自动生成表单的角度包。由于原始问题的答案是基于生成一个新的 formControl 并将其添加到表单中,在我的情况下,这是由 formly 完成的,这就是我努力的原因。
“组件”通常在您要输入新值时起作用(因为这会触发我用来更改模型值的事件),但初始值未正确显示。虽然模型始终具有例如的值“2020-07-05”如果使用占卜检查,则永远不会显示在输入字段中。如果我将模型中的日期转换为 ngOnInit() 中的 NgbDate ({year, month, day}),这仍然是正确的。
Formly 调用我的自定义组件(定义如下),该组件仅包含字段并将预先存在的表单控件(包括模型)和字段配置绑定到输入字段。 The component itself doesn't do much, it contains the necessary HTML for the ngbDatepicker and a function that, when a date is chosen, converts it from an NgbDate ({year, month, day}) to a string ("yyyy-mm -dd") 并确保将其存储在模型中而不是 NgbDate 中。当您单击 fa-calendar 图标时,它还会打开日期选择器:
//formly-datepicker.component.html
<div class="form-group" [ngClass]="{'d-none': to.hidden}">
<!-- Heading -->
<!-- to = TemplateOptions -->
<label for="datepicker">
<strong>
{{to.label}}
<span *ngIf="to.required">*</span>
</strong>
</label>
<!-- Input -->
<div class="input-group">
<input
class="form-control"
placeholder="yyyy-mm-dd"
name="datepicker"
[formControl]="formControl"
[formlyAttributes]="field"
ngbDatepicker
#datepickerInput="ngbDatepicker"
(dateSelect)="inputDateToField($event)"
>
<div class="input-group-append">
<div class="btn btn-outline-light fa fa-calendar" (click)="datepickerInput.toggle()"></div>
</div>
</div>
</div>
<ng-template #customDay let-date>
<div class="datepicker-day btn-light">
{{ date.day }}
</div>
</ng-template>
//formly-datepicker.component.ts
import { Component, } from '@angular/core';
import { NgbDate } from '@ng-bootstrap/ng-bootstrap';
import { FieldType } from '@ngx-formly/core';
@Component({
selector: 'app-formly-datepicker',
templateUrl: './formly-datepicker.component.html',
styleUrls: ['./formly-datepicker.component.scss']
})
export class FormlyDatepickerComponent extends FieldType{
inputDateToField(event: NgbDate){
this.model.session_date = `${event.year}-${event.month}-${event.day}`;
}
}
我尝试在 ngOnInit() 和 ngAfterViewInit() 中操作模型,我尝试设置 startDate,但在这种情况下似乎没有任何帮助。我在这里做什么?
【问题讨论】:
-
您能找到解决方案吗?即使我面临完全相同的问题。当自定义模板是一个简单的文本框时它可以工作,但当我将它更新为
ngbDatepicker -
@Aashwath Acharya 遗憾的是没有。我通常会用我找到的解决方案的详细解释来更新我的问题,但是直到今天我都没有找到这个。
-
它实际上对我有用,我以不正确的格式而不是 YYYY-MM-DD 传递了日期。不同之处可能在于 NgBootstrap 和 Formly 库的配置。已在我的回答中详细说明。
标签: angular datepicker angular-reactive-forms ng-bootstrap angular-formly