【发布时间】:2018-09-26 06:10:07
【问题描述】:
我遇到了一个问题,我尝试为表单组中的一个控件修补值。它永远不会成功。 我将 Angular Material DatePicker 与 moment.js 一起使用
这是 HTML:
<form novalid [formGroup]="desktopSearchForm">
<div class="row-content" *ngIf="dateRange">
<mat-form-field class="desktop-input">
<input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="mobileFromDate" placeholder="From" formControlName="startDate" (focusout)="dateParse(desktopSearchForm.get('startDate'))" />
<mat-datepicker-toggle matSuffix [for]="mobileFromDate"></mat-datepicker-toggle>
<mat-datepicker #mobileFromDate></mat-datepicker>
</mat-form-field>
</div>
</form>
这是我调用的函数(focusout)
this.desktopSearchForm = this.fb.group({
classID: [''],
startDate: [''], //This is the one I want to patch
endDate: [''],
transactionTypeID:['']
})
dateParse(control) {
if (control.value) {
//control.value is a Moment.js Date object
let group = <FormGroup>control.parent;
let TheKey;
Object.keys(group.controls).forEach(key => {
let childControl = group.get(key);
if (childControl === control) { // I found the Control I want to patch
TheKey = key;
}
})
group.patchValue({TheKey:control.value}) //I patch it here.
}
此功能用于将正确的日期格式自动分配回输入字段(图像有许多具有不同名称的日期选择器,例如 startDate、endDate 等)。例如,我在输入框中输入 25111988,当我聚焦时,输入值变为 '25/11/1988'。 但问题是 control.value 永远不会修补正确显示“startDate”的键。
但是如果我把它改成这个并且它可以工作:
group.patchValue({startDate : control.value })
这里还有一个问题是:
如果我将 group.patchValue({startDate : control.value }) 放入:
Object.keys(group.controls).forEach(key => {
let childControl = group.get(key);
if (childControl === control) {
group.patchValue({startDate : control.value })
}
})
然后它不起作用。这就是为什么我把这个补丁函数放在forEach之外。
需要帮助。非常感谢。
【问题讨论】:
-
不应该
(focusout)="dateParse(mobileSearchForm.get('startDate'))"是(focusout)="dateParse(desktopSearchForm.get('startDate'))"吗? (desktopSearchForm而不是mobileSearchForm) -
能否请您创建 stackblitz 来检查问题。
-
@DanDumitru 对不起,我已经编辑了内容,现在焦点正在通过 desktopSearchForm。当我试图复制到这里时,这是一个错字。
-
@JavascriptLover-SKT 是的,我稍后会为此创建一个堆栈闪电战。
-
这个问题更容易理解和很好的解释。 stackoverflow.com/questions/2274242/…
标签: angular angular5 formgroups