How to read Form values in Angular 5

read form values in Angular 5

We are here to learn how to read form values in Angular 5. Forms are mainstay part in business applications. In developing a form, it’s important to create a data-entry experience that guides the user efficiently and effectively through the workflow.


Here are step by step guide how to read form values in angular 5-

Design a form:

Design the html form with the form, input and button controls.

login.component.html

<form #userForm="ngForm" (ngSubmit)="login(userForm)">
  <div class="form-group">
    <label class="control-label" for="username">Username</label>
    <input type="text" class="form-control" placeholder="Username" name="username" ngModel>
  </div>
  <div class="form-group"> 
    <label class="control-label" for="password">Password</label> 
    <input type="text" class="form-control" placeholder="Password" name="password" ngModel>
  </div>
  <button type="submit" class="btn btn-success pull-right">Login</button>
</form>

Import Forms module in app module file:

This is necessary part while reading form values. You must import the necessary modules in Import section of app.module.ts file.

app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { LoginComponent } from './login.component';

@NgModule({
    declarations: [
        LoginComponent
    ],
    imports: [
        FormsModule,
        ReactiveFormsModule,
    ],
    providers: [
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Read form values in component file:

Write code to read the form values on submit function. You will be able to see the form values on form submit.

login.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
    selector: 'login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

    constructor() { }

    ngOnInit() {
        
    }

    login(form: NgForm) {
        // read your form values here
        console.log(form.value);
        alert(form.value);
        // {username: 'username value', password: 'password value'}
    }
}

Login component html form values can be accessed in the login() method on form submit.

Thanks for reading. Any comment or suggestion would be appreciated. Thanks 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *