问题描述
我有一个包含 3 个输入的表单组。第一个输入是时间输入,另外两个是自定义表单组件。我设置了一个 form.patchValue 来更新表单值,如下所示,但是它没有更新 UI,时间输入仍然是空的。
如何使用 patchValue 更新输入?
this.scheduleAutoReportForm = new FormGroup(
{
reportAt: new FormControl( '12:00',Validators.required),days: new FormControl([],email: new FormControl([],[Validators.required])
}
);
this.scheduleAutoReportForm.patchValue({
reportAt: '24:00',days:["2","4"],email: ['placeholder@gmail.com']
});
this.ref.detectChanges();
更新
我进行了实验,结果发现文本框会更新,但时间不会更新。
<div class="modal-header">
<h4 class="h-primary modal-title">Schedule Auto Report</h4>
<mh1-icon-button [icon]="faTimes" [iconClasses]="['btn','btn-sm','mx-0']" iconSize="lg" (click)="closeModal()">
</mh1-icon-button>
</div>
<div class="modal-body card">
<!-- This is where the form starts -->
<form [formGroup]='scheduleAutoReportForm' (ngSubmit)='onSubmit()'>
<div class="row">
<div class="col-3">
<label for="reportAt" ><h5>Send Report At:</h5></label>
<input type="time" name='reportAt' formControlName='reportAt' class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-3">
<label for="test" >test</label>
<input type="text" name='test' formControlName='test' class="form-control" >
</div>
</div>
<div class="row mt-2">
<div class="col-12">
<sentryx-day-selector formControlName="days"></sentryx-day-selector>
</div>
</div>
<div class="row mt-2">
<div class='col-12'>
<sentryx-email-chips formControlName="email"></sentryx-email-chips>
</div>
</div>
<div class="row mt-5">
<div class="col-12">
<button type="submit" class="btn btn-md btn-secondary"
[disabled]="!scheduleAutoReportForm.valid">Submit</button>
<button type="cancel" class="btn btn-md btn-secondary">Cancel</button>
</div>
</div>
</form>
</div>
<div class="modal-footer card">
{{scheduleAutoReportForm.value | json}}
{{schedule | json}}
</div>
解决方法
您是否尝试在修补值后调用 updateValueAndValidity()? 见