Angular 5 Reactive Forms - 一个视图模板中的多个表单

Angular 5 Reactive Forms - multiple forms in one view template

我的想法是在一个视图模板上支持多种形式,然后根据用户交互只显示我需要的一种。

对于初学者,我有一个 HOST 节点和一个 LOCATION 节点 - 都在一个 [formGroup] 下 - 然后我根据需要 show/hide。

问题是我的 HOST 表单总是显示 INVALID 状态 - 即使我触摸它也是如此。但是,一旦我 "touch" 它,我的 LOCATION 形式就是 VALID。这是令人困惑的部分。

这是一个片段:

<form class="popup-dialog form-horizontal" [formGroup]="nodeEditForm" (ngSubmit)="updateNode(nodeEditForm.value)"> 

 <!-- LOCATION -->
 <table [hidden]="nodeType != 'Location'" class="table table-bordered location-node">
  <!-- all location form controls here... -->
 </table>

 <!-- HOST -->
 <table [hidden]="nodeType != 'Host'" class="table table-bordered host-node">
  <!-- all location form controls here... -->
 </table>

 <p>Form value: {{ nodeEditForm.value | json }}</p>
 <p>Form status: {{ nodeEditForm.status | json }} &nbsp; Dirty: {{ nodeEditForm.dirty}} &nbsp; Touched: {{ nodeEditForm.touched}}</p>
  
      <!-- SAVE/CANCEL -->
 <div class="buttons">
  <div style="display: inline;" role-required="Admin" edit-access="true">
   <button class="btn btn-primary btn-sm" [disabled]="!nodeEditForm.valid || !nodeEditForm.dirty" (click)="updateNode($event)">
    <span *ngIf="!isUpdating" >SAVE</span>
    <i *ngIf="isUpdating" class="fa fa-spinner fa-spin"></i>
   </button>
  </div>

  <div style="display: inline;">
   <button class="btn btn-primary btn-sm" (click)="clearNode($event)" >Cancel</button>
  </div>            
 </div>
</form>

在我的 Angular 组件中:

// OnChanges fired first, this.node will be null
ngOnChanges(changes: SimpleChanges){       
  if(changes["node"] != null){
     this.currPage = 1;
     this.initNode();  // all props get assigned empty default values
     this.initForm();
   }
}

initForm() {            
  let grp = this.getFormData(this.node);

  // ADD GROUP CONTROLS FOR FORM !!
  this.nodeEditForm = this.nodeFormBldr.group(grp);

  return;
}

// Assign node properties to form controls; properties initialized in initNode()
  getFormData(node: INode) {

    //this.editXml(); // TO DO     

    return {        
      LocationName: [this.node.LocationName : '', Validators.required],
      LocationType: [this.node.LocationType],
      Address1: [this.node.Address1],
      Address2: [this.node.Address2],
      City: [this.node.City],
      State: [this.node.State],
      Country: [this.node.Country],
      ZipCode: [this.node.ZipCode],
      Phone: [this.node.Phone],
      Email: [this.node.Email],

      ApplicationRoot: [this.hostNode.ApplicationRoot],
      DefaultHostStorage: [this.hostNode.DefaultHostStorage],
      HostName: [this.hostNode.HostName],
      HostIp: [this.hostNode.HostIP],
      IsActive: [this.hostNode.IsActive],        
      XmlData: [this.hostNode.xmlConfig]
    }    
  }

我打赌你的 HostName 表单没有设置 LocationName 字段。因此它始终无效,因为您为 LocationName 设置了 Validators.required。