将值分配回组的Angular PatchValue问题

时间:2018-09-26 06:10:08

标签: angular angular5 formgroups

我遇到了一个问题,其中我试图为表单组中的控件之一的patchValue。而且它永远不会成功。 我将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>

这是我调用的(对焦)功能

 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之外。

需要帮助。非常感谢。

1 个答案:

答案 0 :(得分:1)

您必须将动态键绑定到分配给 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.
}
相关问题