我在 Angular Reactive Forms 应用程序中使用 PrimeNG 日历控件。在我的应用程序中,我在 Primefaces 对话框中有一个带有日历控件的表单。
当在日历控件中输入无效的日期值时,我会在对话框关闭时以编程方式将控件的值更新为预定义的回滚日期值,以便在再次显示时表单处于有效状态。
但是,我发现以编程方式更新日历控件的值并不能始终使用新值更新 UI。
我正在使用 FormGroup 并尝试了 setValue 和 patchValue。我还尝试在日历控件上显式使用 setValue 和 patchValue 以及 formGroup 的重置方法。问题仍然存在。
只是想知道是否有人可以建议我在代码中哪里出错了?
我在http://plnkr.co/edit/xc4ygZ?p=info创建了一个 plunker来说明一个例子。角度组件和模板的代码包含在下面......
import {
Component
} from '@angular/core';
import {
FormBuilder
} from '@angular/forms';
import {
FormGroup
} from '@angular/forms';
import {
OnInit
} from '@angular/core';
import {
Validators
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: 'app/app.template.html'
})
export class AppComponent {
birthDate: Date;
form: FormGroup;
formErrors = {
'setdate': '',
};
validationMessages = {
'setdate': {
'required': 'Set date is required.',
'invalidDate': 'Invalid Date.'
},
};
constructor(private fb: FormBuilder) {
this.birthDate = new Date();
}
ngOnInit(): void {
this.buildForm();
}
onSubmit(): void {
}
setSetDate(): void {
let today = new Date();
this.form.patchValue({
setdate: today
});
}
private buildForm(): void {
this.form = this.fb.group({
setdate: [this.birthDate, [Validators.required]]
});
this.form.valueChanges
.subscribe(data => this.onValueChanged(data));
//this.onValueChanged();
}
private onValueChanged(data ? : any): void {
let _self = this;
if (!this.form) {
return;
}
const form = this.form;
console.log("onValueChanged()");
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + '\n';
}
}
}
}
}
<p> Enter a date that is invalid, e.g. edf. Then try clicking the button to programmatically reset the date</p>
<p> The UI for the calendar control does not consistently update with the new date. </p>
<form autocomplete="off" [formGroup]="form" novalidate (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="setdate" class="control-label col-xs-4">Set Date</label>
<div>
<p-calendar #theDate id="setdate" formControlName="setdate" showTime="true" hourFormat="24" dateFormat="dd-mm-yy" [showIcon]="true" placeholder="Set Date" required>
</p-calendar>
<p>SetDate Value :: {{ theDate.value }}</p>
<p>SetDate Valid :: {{ this.form.controls['setdate'].valid }}</p>
<p>SetDate Errors :: {{ this.form.controls['setdate'].errors | json }}</p>
</div>
<div *ngIf="formErrors.setdate" class="alert alert-danger">
{{ formErrors.setdate }}
</div>
</div>
<button type="button" class="btn" (click)="setSetDate()">Test SetDate</button>
</form>