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 :
JavaScript
x
5
1
<form [formGroup]="regForm" >
2
<label for="txtFName">First Name</label>
3
<input type="text" id="txtFName"/>
4
</form>
5
component.ts :
JavaScript
1
23
23
1
import { Component } from "@angular/core"
2
import { FormControl, FormGroup, FormBuilder, Validator, Validators,ReactiveFormsModule } from "@angular/forms";
3
import { customer } from '../model/customerModel'
4
import { Router } from "@angular/router";
5
6
export class regComponent
7
{
8
private Customer:customer;
9
private regForm:FormGroup;
10
private firstName:FormControl;
11
12
constructor (private formBuilder:FormBuilder,private router:Router)
13
{
14
15
this.firstName=new FormControl('',[Validators.required])
16
17
this.regForm=formBuilder.group({
18
firstName:this.firstName
19
})
20
21
console.log(this.regForm.value);
22
}
23
here I am getting empty value in the console. Please help in this regard
Advertisement
Answer
Add formControlName
to input
JavaScript
1
2
1
<input type="text" id="txtFName" formControlName="firstName" />
2
Now access the value by name
JavaScript
1
2
1
this.regForm.get('firstName').value
2