0

I am trying to validate a Angular reactive form , where I am trying to catch the value of the input field and if input field is not validated I will show the message

<span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid &&  signForm.control['fname'].touched "> Enter your Name </span>

.. but I am getting error - >

 ERROR TypeError: Cannot read property 'fname' of undefined

I am putting all the details of the form

html code -

<form [formGroup]='signupForm' (ngSubmit)="PostData(signupForm)">
       <h2 class="text-center"> Registeration Form </h2>
      <br/>
      <div class="form-group">
       <input type="text" formControlName='fname'  placeholder="First Name">
       <span *ngIf="signupForm.control['fname'].haserror(required) && signForm.control['fname'].invalid &&  signForm.control['fname'].touched "> Enter your Name </span>
      </div>  

 <input type="submit" value="Post Data" [disabled]='!signupForm.valid'>
          </div>
          </form> 

ts file code ->

export class ReactiveComponent implements OnInit {

  signupForm: FormGroup;
  FirstName: string = '';
  LastName: string = '';
  Eamil: string = '';
  Password: string = '';
  constructor(public frmbuilder: FormBuilder) { // formBuilder assign all the formcontrol to formgroup
    this.signupForm = frmbuilder.group({
    fname: ['',Validators.compose([Validators.required , Validators.minLength(4)])],  // FormControl  Used to bring input value to the ts file 
    lname: ['', Validators.required],
    Emailid: ['', [Validators.required , Validators.email]],
    userpassword: ['', Validators.required ]
});


   }

  ngOnInit() {
  }

  PostData(signupForm: any) {
    console.log(signupForm.controls);
    this.FirstName  = signupForm.controls.fname.value;
    this.LastName  = signupForm.controls.lname.value;
    this.Eamil  = signupForm.controls.Emailid.value;
    this.Password  = signupForm.controls.userpassword.value;

  }
1
  • signupForm.get('fname') ? Commented Aug 28, 2018 at 9:25

2 Answers 2

1

it should be,

hasError always be in camelCase

<span *ngIf="signupForm.get('fname').hasError(required) && signupForm.get('fname').invalid &&  signupForm.get('fname').touched "> Enter your Name </span>
Sign up to request clarification or add additional context in comments.

Comments

1

Try

<span *ngIf="signupForm.controls['fname'].hasError('required')">Firstname is Required!! </span>

notice the way you called the fname control, do signupForm.controls instead of signupForm.control

1 Comment

*ngIf="signupForm.controls['fname'].invalid" also enough.