Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read form values in controller?

Tags:

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

like image 668
Dhileepan S J Avatar asked Dec 15 '17 07:12

Dhileepan S J


People also ask

How do I find controller model value?

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.

How do I get value from FormCollection?

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.


2 Answers

Add formControlName to input

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

Now access the value by name

this.regForm.get('firstName').value 
like image 83
Sachila Ranawaka Avatar answered Sep 20 '22 02:09

Sachila Ranawaka


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 
like image 20
abedfar Avatar answered Sep 23 '22 02:09

abedfar