繁体   English   中英

Angular2:如何在嵌套的formBuilder表单上访问formControl值

[英]Angular2: how to access a formControl value on a nested formBuilder form

如何在不使用[ngModel]情况下获取this.resFormGroup.patientName.lastname.value的值?

在HTML <form>标记中, name="resForm"[formGroup]="resFormGroup"#resNgForm="ngForm"的目的是什么?

我需要模板引用变量#resNgForm因为我有[formGroup]="resFormGroup"吗?

这是我的组成部分:

// FormBuilder
this.resFormGroup = this.formBuilder.group({
  patientName: this.formBuilder.group({
    firstname: ['', Validators.required],
    lastname: ['', Validators.required]
  }),
  address: this.formBuilder.group({
    street: [],
    zip: [],
    city: []
  })
});

这是我的模板:

<form name="resForm" [formGroup]="resFormGroup" (ngSubmit)="onSubmit()" #resNgForm="ngForm">
  <fieldset formGroupName="patientName">
      <legend>Name</legend>
  <label>Firstname:</label>
  <input type="text" formControlName="firstname" [(ngModel)]="myFirstName">

  <label>Lastname:</label>
  <input type="text" ***formControlName="lastname"***>
  </fieldset>

  <fieldset formGroupName="address">
      <legend>Address</legend>
      <label>Street:</label>
      <input type="text" formControlName="street">

      <label>Zip:</label>
      <input type="text" formControlName="zip">

      <label>City:</label>
      <input type="text" formControlName="city">
  </fieldset>

  <button type="submit" class="btn btn-primary" [disabled]="!resNgForm.valid">Submit</button>

我的提交按钮:

 onSubmit() { 
   console.log("Submit button pressed [ngModel: " + this.myFirstName + "]    [Form: " + this.resFormGroup.controls["patientName"].dirty + "]"); 
 }

使用[ngModel] ,我可以获得名字; 我还可以访问formGrouppatientNamedirty属性。

基于这个关于动态表单的教程,他们使用一种非常简单的方法来显示整个表单的值,而不需要[ngModel]。

如何获取formBuilder表单值? 答案是'this.myForm.value'。

示例代码

例如:

onSubmit(model: ResCrud) {  
    console.log("Nested Control: " + JSON.stringify(this.resFormGroup.value));
}

它在Web控制台中的外观

angular formbuilder嵌套值示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM