0
votes

I am using angular 2 and having stuck in using FormBuilder and FormGroup . On submit of form I am passing the form.value which will of type FormGroup.

When I am going to access my properties, and restarting the lite server , it is not starting the app and throwing a exception that userName property are not defined FieldGroup.

code snippet are :

import { Component } from '@angular/core';
import { FormBuilder,FormGroup} from '@angular/forms';
import { LoginService } from '../../services/login.service'; 

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

export class LoginComponent  { 

    form:FormGroup;


    constructor(
        private formBuilder:FormBuilder){

    }
    ngOnInit() {
        this.form=this.formBuilder.group({
            userName:this.formBuilder.control(''),
            password:this.formBuilder.control(''),
            remember:this.formBuilder.control(''),
            textCaptcha:this.formBuilder.control('')
        });
    }
onSubmit(loginForm:FormGroup){
        alert(`UserName is `+loginForm+`
            and password is `+loginForm);   
    }
}

HTML

<form id="loginform" class="form-horizontal" role="form" [formGroup]="form" (ngSubmit) = "onSubmit(form.value)">


<div style="margin-bottom: 25px" class="input-group">
      <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
      <input id="password" ngModel  type="password" class="form-control" name="password" placeholder="password" formControlName="password">
  </div>
 <div class="col-sm-12 controls">
    <button type="submit" class="btn btn-primary">Login  </button>
    <a id="btn-login" href="#" (click)="reset()" class="btn btn-warning">Reset  </a>
  </div>

If I add in alert the property is working but when restarting server it throwing the error and has to remove the property. So I am not able to use Form values

alert(`UserName is `+loginForm.userName+`
            and password is `+loginForm.password);

Error is

app/components/login/login.component.ts(50,34): error TS2339: Property 'userName
' does not exist on type 'FormGroup'.
2
I don't think you are accessing the value properly. Try something like this.loginForm.get('userName'), or this.loginForm.get('userName').value. Or, even this.loginForm.controls.userName, or this.loginForm.controls.userName.value. - R. Richards

2 Answers

0
votes

Try this: loginForm.value.userName

The loginForm.value contains the object with all the properties like:

{
  userName: "asdfasdf",
  password: "asdfas"
}
0
votes

I resolved the issue by Creating an interface and passing the interface reference to form submit function

interface User{
    userName:string,
    password:string,
    textcaptcha:string,
    remember:boolean
}

onSubmit(loginForm:User){
        alert(loginForm.userName);
    }

And restarting server is not throwing any error now