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
In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller with views, using Entity Framework, and then click Add. Select Movie (MvcMovie. Models) for the Model class.
The FormCollection class will automatically receive the posted form values in the controller action method in key/value pairs. Keys & values can be accessed using key names or index. Right-click on Index method in HomeController.
Add formControlName
to input
<input type="text" id="txtFName" formControlName="firstName" />
Now access the value by name
this.regForm.get('firstName').value
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With