我遇到了一个问题,我试图通过patchValue获取窗体组中的一个控件。但它从来没有成功过。我在moment.js中使用角度材质DatePicker
下面是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之外的原因。
需要帮助。非常感谢。
发布于 2018-09-26 14:44:34
你必须在你赋值给TheKey的地方绑定动态密钥,你可以这样做,
唯一的更改是从{TheKey:control.value}到{TheKey:control.value}
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.
}
https://stackoverflow.com/questions/52511039
复制相似问题