Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all values of a form in angular2

Tags:

html

angular

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.

like image 511
stack questions Avatar asked May 02 '18 10:05

stack questions


People also ask

How to get the value of the form in angular?

- GeeksforGeeks How to get the value of the form in Angular ? In this article, we are going to see how to get value from the form in Angular 10. We will use AbstractControl value property to get the form value in an object. In app.component.html make a form using ngForm directive. Serve the angular app using ng serve to see the output.

What is the use of input form in angular?

Form contains multiple html input elements to take input from the user. button allows the user to submit the from to backend API an d it calls click binding event. In Angular, View is html template and controller is an typescript component. Reading input text is basic concept every Angular developer need to know.

How to enable validation in formgroup in angular?

We can access its value using get () method. To validate a form control in FormGroup, angular provides Validators class. We can use it to enable validation in form control as given below. To check validity of form control, we can write a method for a form control as given below. Now in HTML template we can access validity state as userName.invalid.

How to design forms using two-way binding in Angular 2?

Angular 2 - Forms. Angular 2 can also design forms which can use two-way binding using the ngModel directive. Let’s see how we can achieve this. Step 1 − Create a model which is a products model. Create a file called products.ts file. Step 2 − Place the following code in the file.


2 Answers

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);
}
like image 116
Michelangelo Avatar answered Oct 13 '22 18:10

Michelangelo


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

like image 11
Pranay Rana Avatar answered Oct 13 '22 19:10

Pranay Rana