Angular表单持久化:组件销毁后恢复表单

Angular Form persistence: restore Form after the component was destroyed

我正在使用 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 [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>

我想实现一种表单持久化机制来满足以下用户故事:

  1. 用户开始使用表单。
  2. 他使某些字段无效并看到验证消息。
  3. 然后他转到另一个页面,Form被破坏了。
  4. 然后他返回到表单页面。
  5. 表单已恢复,用户看到了他的脏字段以及 p.2 中的验证消息。

我尝试以如下方式通过全局服务保留表单:

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
}

但是不行。是否有一些方法可以允许保留整个表单并使其可重复使用其所有特定属性?

这似乎是对 this.newDeviceForm 的引用的问题 这里有一个使用你提供的案例的演示,我已经简化了服务 class.

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));
  }
}