Getting all values of a form in angular2

2020-07-13 00:07发布

问题:

I can get the value of a form using the following code:

<input type="text" formControlName="subscriptionFormName" id="subscriptionFormName" #UserName class="form-control" mdbInputDirective>
<button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="OnSubmit(UserName.value)" mdbWavesEffect>Send
    <i class="fa fa-paper-plane-o ml-1"></i>
</button>

but what I need is to get all values of a form so I can do this:

<button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="OnSubmit(allFormValues)" mdbWavesEffect>Send
    <i class="fa fa-paper-plane-o ml-1"></i>
</button>

user: User;
ObSubmit(values) {
    user.UserName = values.UserName;
    user.Password = values.Password;
    ......
}

below is the whole code:

<div class="row">
  <div class="col-md-12 text-left">

    <form [formGroup]="subscriptionForm">
      <h3 style="color: gray; text-align: center;">Registration</h3>

      <div class="row">
        <div class="col-md-6">
          <div class="md-form">
            <i class="fa fa-user prefix grey-text"></i>
            <input type="text" formControlName="UserName" id="UserName" class="form-control" mdbInputDirective>
            <label for="UserName">Your UserName</label>
          </div>
          <br>
          <div class="md-form">
            <i class="fa fa-user prefix grey-text"></i>
            <input type="text" formControlName="FirstName" id="FirstName" class="form-control" mdbInputDirective>
            <label for="FirstName">Your First name</label>
          </div>
        </div>
        <div class="col-md-6">
          <div class="md-form">
            <i class="fa fa-user-secret prefix grey-text"></i>
            <input type="password" id="Password" formControlName="Password" class="form-control" mdbInputDirective>
            <label for="Password">Your password</label>
          </div>
          <br>
          <div class="md-form">
            <i class="fa fa-user-user prefix grey-text"></i>
            <input type="text" id="LastName" formControlName="LastName" class="form-control" mdbInputDirective>
            <label for="LastName">Your Last name</label>
          </div>
        </div>
      </div>
      <br>
      <div class="row">
        <div class="col-md-12">
          <div class="md-form">
            <i class="fa fa-envelope prefix grey-text"></i>
            <input type="email" id="Email" formControlName="Email" class="form-control" mdbInputDirective>
            <label for="Email">Your Email</label>
          </div>
          <br>
          {{subscriptionForm.value|json}}
          <br>
          <div class="text-center">
            <button class="btn btn-indigo btn-lg btn-block waves-light" type="button" (click)="OnSubmit()" mdbWavesEffect>Send
              <i class="fa fa-paper-plane-o ml-1"></i>
            </button>
          </div>
        </div>
      </div>
    </form>

  </div>
</div>

import { User } from './../../shared/user.model';
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
  subscriptionForm: FormGroup;
  user: User;

  constructor(private fb: FormBuilder) {
    this.subscriptionForm = fb.group({
      UserName: ['', Validators.required],
      Password: ['', Validators.required],
      Email:    ['', Validators.required, Validators.email],
      FirstName: ['', Validators.required],
      LastName: ['', Validators.required]
    });
  }

  ngOnInit() {
  }

  OnSubmit() {
   this.user = this.subscriptionForm.value;
   console.log(this.user);
  }

}

When I use the #subscriptionForm="ngForm" I get an error. Probably because of the [formGroup]="subscriptionForm". I don't know what a reactive form or other forms. I'll study that after this but can you help me with this? Thank you.

回答1:

Working Demo based on your input in question.

Dont mix Reactive form approach with Template Driven approach, otherwise you end up will lot of problem. Follow one of them in one component. As you are following Reactive form follow that only.

that means you cannot use #subscriptionForm="ngForm" as its template driven form approach.


I suggest you make use of reactive form approach , so you can get all form value in once by doing this

 user = userForm.value ;

but for that you need to crate from by yourself and do like this

<form [formGroup]="userForm">
  <div class="form-group">
    <label class="center-block">Name:
      <input class="form-control" formControlName="name">
    </label>
  </div>
</form>

ts file

 User:user;
 constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    //form control name should match with User class property name
    this.userForm= this.fb.group({
      name: ['', Validators.required ],
      street: '',
      ..other property
    });
  }

  submit() {
   this.user = userForm.value;
   //if property doesnt match then do this 
   this.user.Name = this.userForm.get('name').value;
   ..do for all property 
  }

Cannot explain in detail , you should follow this : https://angular.io/guide/reactive-forms



回答2:

The accepted answer is outdated and does not work anymore for Angular 8+, this works nicely to get all your values:

for (const field in this.myForm.controls) { // 'field' is a string
  console.log(this.myForm.controls[field].value);
}


回答3:

Use NgModel to get the data of each tag in a form Try this: add attribute to input tag [(ngModel)]="password"

Component:
password; 
password_com;

this.password_com=this.password;


标签: html angular