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
Advertisement
Answer
Add formControlName
to input
<input type="text" id="txtFName" formControlName="firstName" />
Now access the value by name
this.regForm.get('firstName').value