即使是新表单组也不会清除Angular 4 Form值

时间:2018-03-17 09:01:02

标签: angular angular4-forms

我在Angular应用程序中有一个表单类,其代码如下:

import { 
  OnInit, 
  OnDestroy, 
  Injector 
}                                   from "@angular/core";
import { 
  FormBuilder, 
  FormGroup, 
  Validators 
}                                   from "@angular/forms";
import { 
  Observable, 
  Subscription 
}                                   from "rxjs";
import { inject }                   from "@angular/core/testing";

import { ActivatedRoute }           from '@angular/router';
import { TranslateService }         from 'ng2-translate';


import { AccessRoleSandbox }        from '../../role.sandbox';
import { AccessPermissionSandbox }  from '../../../permission/permission.sandbox';
import RoleForm                     from '../../models/role-form.model';
import Role                         from "../../models/role.model";
import Permission                   from "../../../permission/models/permission.model";

/**
 * Role form container class
 * 
 * @export
 * @class RoleFormContainer
 */
export class RoleFormContainer implements OnInit, OnDestroy{

  /**
   * Translate service
   * 
   * @protected
   * @type {TranslateService}
   * @memberof RoleFormContainer
   */
  protected translateService: TranslateService;

  /**
   * Form Builder
   * 
   * @protected
   * @type {FormBuilder}
   * @memberof RoleFormContainer
   */
  protected formBuilder: FormBuilder;

  /**
   * Activated route
   * 
   * @protected
   * @type {ActivatedRoute}
   * @memberof RoleFormContainer
   */
  protected route: ActivatedRoute;

  /**
   * Role create/update form
   * 
   * @type {FormGroup}
   * @memberof UpdateRoleContainer
   */
  public form: FormGroup;

  /**
   * Access role sandbox
   * 
   * @protected
   * @type {AccessRoleSandbox}
   * @memberof RoleFormContainer
   */
  protected accessRoleSandbox: AccessRoleSandbox;

  /**
   * Access permission sandbox
   * 
   * @protected
   * @type {AccessPermissionSandbox}
   * @memberof RoleFormContainer
   */
  protected accessPermissionSandbox: AccessPermissionSandbox;

  /**
   * Role ID
   * 
   * @private
   * @type {number}
   * @memberof UpdateRoleContainer
   */
  protected roleId: number;

  /**
   * All permissions object
   * 
   * @type {Array<any>}
   * @memberof CreateRoleContainer
   */
  public allPermissions: Array<any>;

  /**
   * Selected permissions
   * 
   * @type {Array<any>}
   * @memberof RoleFormContainer
   */
  public selectedPermissions: Array<any> = [];

  /**
   * Multiselect dropdown settings
   * 
   * @type {*}
   * @memberof CreateRoleContainer
   */
  public multiselectSettings: any;

  /**
   * Subscriptions
   * 
   * @type {Array<Subscription>}
   * @memberof RoleFormContainer
   */
  public subscriptions: Array<Subscription>;

  /**
   * Form title
   * 
   * @type {string}
   * @memberof RoleFormContainer
   */
  public formTitle: string;

  /**
   * Loading icon on submit button decider
   * 
   * @type {Observable<any>}
   * @memberof RoleFormContainer
   */
  public loadingObservable$: Observable<any>;

  /**
   * Creates an instance of RoleFormContainer.
   * 
   * @param {Injector} injector 
   * @memberof RoleFormContainer
   */
  constructor(
    injector: Injector
  ) {
      this.accessRoleSandbox        = injector.get(AccessRoleSandbox);
      this.accessPermissionSandbox  = injector.get(AccessPermissionSandbox);
      this.translateService         = injector.get(TranslateService);
      this.formBuilder              = injector.get(FormBuilder);
      this.route                    = injector.get(ActivatedRoute);

      this.createForm();
  }

  /**
   * On Init container
   * 
   * @memberof CreateRoleContainer
   */
  ngOnInit() {

  }

  /**
   * Unsubscribe from all Observables
   * 
   * @memberof CreateRoleContainer
   */
  public ngOnDestroy() {

  }

  /**
   * Register subscriptions
   * 
   * @memberof CreateRoleContainer
   */
  public registerSubscriptions() {
    const allPermissions$ = this.accessPermissionSandbox.permissions$;
    const viewingRole$    = this.accessRoleSandbox.viewingRole$;

    const routerSubscription = this.route.params.subscribe(params => {
      if(params && params.hasOwnProperty('id')) {
        this.roleId = params['id'];
        this.accessRoleSandbox.viewRole(this.roleId);
      }
    });

    const viewRoleSubscription = viewingRole$.switchMap(
      () => allPermissions$,
      (role: Role, perms: Array<Permission>) => {
        this.allPermissions = this.normalizePermissions(perms);
        return role;
      }
    ).subscribe(role => this.updateFormValues(role));

    this.subscriptions = [routerSubscription, viewRoleSubscription];
  }

  /**
   * Un-register subscriptions
   * 
   * @memberof RoleFormContainer
   */
  public unregisterSubscriptions() {
    this.subscriptions.forEach(sub => sub.unsubscribe());
  }

  /**
   * Create form
   * 
   * @memberof RoleFormContainer
   */
  private createForm() {
    this.form = this.getForm();
  }

  /**
   * Get form
   * 
   * @private
   * @returns {FormGroup} 
   * @memberof RoleFormContainer
   */
  private getForm(): FormGroup {
    return this.formBuilder.group({
      name:         ["", Validators.required],
      sort:         ["", Validators.required],
      status:       ["", Validators.required]
    });
  }

  /**
   * Update form values
   * 
   * @param {Role} role 
   * @memberof RoleFormContainer
   */
  private updateFormValues(role: Role) {
    if(role) {
      this.form.setValue({
        name:           role.name,
        sort:           role.sort,
        status:         role.status
      });
    }
  }
}

这是html文件

<div class="card">
  <form [formGroup]="form" novalidate (ngSubmit)="onSubmit($event, form.value)">
    <div class="card-header">
      <i class="fa fa-tag"></i> {{ formTitle }}
    </div>
    <div class="card-body">
      <div class="row">
        <div class="col-sm-8">
          <div class="form-group row">
            <label class="col-md-3 col-form-label" for="text-input">{{'accessRole.lbl.roleName' | translate}}*</label>
            <div class="col-md-9">
                <div class="input-group">
                  <input 
                  type="text" 
                  id="name" 
                  name="name" 
                  class="form-control" 
                  placeholder="{{'lbl.enter' | translate}} {{'accessRole.lbl.roleName' | translate}}..." 
                  formControlName="name"
                  >
                  <div class="input-group-append">
                    <span class="input-group-text"><i class="fa fa-tag"></i></span>
                  </div>
                </div>
            </div>
          </div>
          <div class="form-group row">
            <label class="col-md-3 col-form-label" for="text-input">{{'accessRole.lbl.sort' | translate}}*</label>
            <div class="col-md-9">
                <div class="input-group">
                  <input 
                  type="number" 
                  id="sort" 
                  name="sort" 
                  class="form-control" 
                  placeholder="{{'lbl.enter' | translate}} {{'accessRole.lbl.sort' | translate}}..." 
                  formControlName="sort"
                  >
                  <div class="input-group-append">
                    <span class="input-group-text"><i class="fa fa-sort-numeric-desc"></i></span>
                  </div>
                </div>
            </div>
          </div>
          <div class="form-group row">
            <label class="col-md-3 col-form-label" for="text-input">{{'accessRole.lbl.active' | translate}}</label>
            <div class="col-md-9 centered-checkbox">
              <label class="switch switch-text switch-primary-outline-alt">
                <input type="checkbox" class="switch-input" formControlName="status">
                <span class="switch-label" data-on="Yes" data-off="No"></span>
                <span class="switch-handle"></span>
              </label>
            </div>
          </div>
          <div class="form-group row">
            <label class="col-md-3 col-form-label" for="text-input">{{'accessRole.lbl.associatedPermissions' | translate}}</label>
            <div class="col-md-9 centered-checkbox">
                <angular2-multiselect [data]="allPermissions" [(ngModel)]="selectedPermissions" 
                  [settings]="multiselectSettings"
                  formControlName="permissions">
                </angular2-multiselect>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="card-footer">
      <button class="btn btn-outline-primary px-3" [disabled]="form.invalid" type="submit">
        {{'btn.lbl.submit' | translate}}
      </button>
        <button type="button" class="btn btn-outline-danger" routerLink="/admin/access/role/list"><i class="fa fa-arrow-left"></i> {{'btn.lbl.goBack' | translate}}</button>
    </div>
  </form>
</div>

此类由create-role.container.tsupdate-role.container.ts组件扩展。它们都有单独的html文件,表单在这些文件中呈现。

问题是,我要更新表单以更新和角色,然后再回到列表中。然后我转到创建页面,表单值没有被清除,你可以看到我在构造函数中从scrach构建表单。

1 个答案:

答案 0 :(得分:0)

我找到了答案,因为我为viewRole $设置了可观察性。因此,当我们每次进入表单时,此订阅都会启用,并会更新viewingRole $的最后状态。