我是usig FormBuilder
在我的 Angular 5.1.2 项目中有一个简单的表单:
ngOnInit() {
const formSettings = {
name: ['', [Validators.required, Validators.maxLength(50), this.nameValidator]],
deviceType: ['', [Validators.required]],
description: ['']
};
this.newDeviceForm = this.formBuilder.group(formSettings);
}
Form的模板如下:
<form [formGroup]="newDeviceForm">
<mat-form-field>
<input matInput formControlName="name" name="name">
<mat-error *ngIf="newDeviceForm.get('name').hasError('required')">
Device Name is required
</mat-error>
<mat-error *ngIf="newDeviceForm.get('name').hasError('maxlength')">
Device Name should be no more than 50 characters
</mat-error>
</mat-form-field>
<!-- ... -->
<mat-form-field>
<input matInput formControlName="description" name="description">
</mat-form-field>
</form>
我想实现Form持久性机制来满足以下用户故事:
我尝试通过以下方式持久保存表单:
ngOnInit() {
if(this.devicesService.newDeviceForm) { // form caching
this.newDeviceForm = this.devicesService.newDeviceForm;
return;
}
const formSettings = { /* ... */ };
this.newDeviceForm = this.formBuilder.group(formSettings);
this.devicesService.registerForm(this.newDeviceForm); // populate DevicesService.newDeviceForm
}
但它不起作用。是否有一些方法可以保持整个表单并使其具有所有特定属性的可重用性?
答案 0 :(得分:1)
对this.newDeviceForm
的引用似乎存在问题
在这里,你有一个使用你提供的案例的演示,我简化了服务类。
https://stackblitz.com/edit/angular-mjyjco
class DeviceService {
private _deviceForm: FormGroup = null;
constructor() {}
registerForm(form: FormGroup): void {
this._deviceForm = form;
}
restoreForm(): FormGroup {
return this._deviceForm;
}
}
class NewDeviceComponent implements OnInit, OnDestroy {
public newDeviceForm: FormGroup = null;
constructor(public formBuilder: FormBuilder, public deviceService: DeviceService) {}
ngOnInit() {
if (this.deviceService.restoreForm() != null) {
this.newDeviceForm = this.deviceService.restoreForm();
} else {
const formSettings = {
name: ['', [Validators.required, Validators.maxLength(50)]],
deviceType: ['', [Validators.required]],
description: ['']
};
this.newDeviceForm = this.formBuilder.group(formSettings);
}
}
ngOnDestroy() {
this.deviceService.registerForm(Object.assign(new FormGroup({}), this.newDeviceForm));
}
}