简体   繁体   English

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

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

How can I get the value of this.resFormGroup.patientName.lastname.value without using [ngModel] ? 如何在不使用[ngModel]情况下获取this.resFormGroup.patientName.lastname.value的值?

What are the purpose of name="resForm" , [formGroup]="resFormGroup" and #resNgForm="ngForm" in the HTML <form> tag? 在HTML <form>标记中, name="resForm"[formGroup]="resFormGroup"#resNgForm="ngForm"的目的是什么?

Do I need the template reference variable #resNgForm since I have the [formGroup]="resFormGroup" ? 我需要模板引用变量#resNgForm因为我有[formGroup]="resFormGroup"吗?

This is my component: 这是我的组成部分:

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

This is my template: 这是我的模板:

<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>

My submit button: 我的提交按钮:

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

With [ngModel] , I can get the first name; 使用[ngModel] ,我可以获得名字; I can also access the dirty attribute of the formGroup 's patientName . 我还可以访问formGrouppatientNamedirty属性。

Based on this tutorial about dynamic form , they used a very simple way to show the values of the whole form without [ngModel]. 基于这个关于动态表单的教程,他们使用一种非常简单的方法来显示整个表单的值,而不需要[ngModel]。

How to get the formBuilder form values? 如何获取formBuilder表单值? The answer is 'this.myForm.value'. 答案是'this.myForm.value'。

Example code 示例代码

For example: 例如:

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

How it looks in the web console 它在Web控制台中的外观

angular formbuilder嵌套值示例

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

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