Angular Form持久性:在组件被销毁后恢复Form

时间:2018-01-20 00:50:43

标签: angular angular-forms

我是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持久性机制来满足以下用户故事:

  1. 用户开始使用Form。
  2. 他使某些字段无效并看到了验证消息。
  3. 然后他走到另一页,表格已被摧毁。
  4. 然后他回到表格页面。
  5. 表单已恢复,用户在第2页的验证消息中看到了他的脏字段。
  6. 我尝试通过以下方式持久保存表单:

    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
    }
    

    但它不起作用。是否有一些方法可以保持整个表单并使其具有所有特定属性的可重用性?

1 个答案:

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