27

I am beginner in Angular 2 and I am trying get a value of textbox in component and I really don't know how to get it.

HTML :

<form [formGroup]="regForm" >
                <label for="txtFName">First Name</label>
                <input type="text" id="txtFName"/>
</form>

component.ts :

import { Component } from "@angular/core"
import { FormControl, FormGroup, FormBuilder, Validator, Validators,ReactiveFormsModule } from "@angular/forms";
import { customer } from '../model/customerModel'
import { Router } from "@angular/router";

export class regComponent
{
    private Customer:customer;
    private regForm:FormGroup;
    private firstName:FormControl;

    constructor (private formBuilder:FormBuilder,private router:Router)
    {

        this.firstName=new FormControl('',[Validators.required])

        this.regForm=formBuilder.group({
        firstName:this.firstName
    })

console.log(this.regForm.value);
}

here I am getting empty value in the console. Please help in this regard

Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
Dhileepan S J
  • 285
  • 1
  • 3
  • 5
  • Possible duplicate of [Get access to FormControl from the custom form component in Angular](https://stackoverflow.com/questions/44731894/get-access-to-formcontrol-from-the-custom-form-component-in-angular) – Sajeetharan Dec 15 '17 at 08:58

3 Answers3

55

Add formControlName to input

<input type="text" id="txtFName" formControlName="firstName" />

Now access the value by name

this.regForm.get('firstName').value
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
5

For below control, named email:

ngOnInit() {
    this.contactForm = this.formBuilder.group({
      email: [null, Validators.compose([Validators.required])]
    });
  }

Access by the name you gave to the control:

this.formGroup.controls['email'].value
abedfar
  • 1,989
  • 24
  • 21
3

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


@Component({
  selector: 'demo-app',
  templateUrl: 'app/app.component.html'
})

export class regComponent implements OnInit {

private regForm:any;
    constructor(private formBuilder: FormBuilder) { 
    }
    ngOnInit(){
        this.regForm=formBuilder.group({
          firstName:['', Validators.required]
         })
    }

     saveUser() {
        if (this.regForm.dirty && this.regForm.valid) {
          alert(`FirstName: ${this.regForm.value.firstName}`);
        }
      }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<form [formGroup]="regForm" (submit)="saveUser()" >
          <label for="txtFName">First Name</label>
          <input type="text" id="txtFName"  formControlName="firstName" #firstName="ngControl"/>
          <button type="submit" [disabled]="!userForm.valid">Submit</button>
        </form>
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57