如何以反应形式退出递归调用 valueChanges

How to exit from recursive call in reactive form valueChanges

我正在观察 formControlvalueChanges。表单控件是一个date picker。选择日期后,我会尝试将其从原始 MM-dd-yyyy 格式重新格式化为 yyyy-MM-dd。我是直接修改表单控件的值。所以它给了我一个递归调用错误。显然是真的。有什么解决办法吗?

代码:

this.parentForm.controls['myControlName'].valueChanges.subscribe((val)=>{
this.parentForm.controls['myControlName'].setValue(this._datePipe.transform(new Date(val), 'yyyy-MM-dd'));
});

<input #inputDate type="text" class="form-control" placeholder="Select date"
  [formControl]="parentForm.controls['myControlName']"
  [value]="selectedDate | date : 'MM-dd-yyyy'"/>
  <datepicker [ngModel]="selectedDate" [minDate]="minDate"
    [maxDate]="maxDate"
    [showWeeks]="false"
    [startingDay]="1"
    (selectionDone)="onSelectionDone($event)">
  </datepicker>

错误:

EXCEPTION: Error in ./DatePickerComponent class DatePickerComponent - inline template:13:8 caused by: too much recursion error_handler.js:54 ORIGINAL EXCEPTION: too much recursion

由于表单控件的setValue方法默认会引发valueChange事件,所以你会运行陷入死循环。您可以将 emitEvent 设置为 false 以防止它。

this.parentForm.controls['myControlName'].setValue(this._datePipe.transform(new Date(val), 'yyyy-MM-dd'), { emitEvent: false });