angular formbuilder can't find formgroup

4.4k views Asked by At

I'm trying to use formbuilder to reduce quite a bit of code on my form component, however I can't get it to work, no matter what I do, I keep getting 'Cannot read property 'invalid' of undefined', the code is down below, am I missing something?

component.html

<form [formGroup]="myForm" class="mt-3" (ngSubmit)="onSubmit()" novalidate>
<fieldset formGroupName="name">

    <div class="form-group" [ngClass]="{'has-danger': firstName.invalid && (firstName.dirty || firstName.touched), 'has-success': firstName.valid && (firstName.dirty || firstName.touched)}">
        <label>First Name</label>
        <input type="text" class="form-control" formControlName="firstName">
    </div>

    <div class="form-group" [ngClass]="{'has-danger': lastName.invalid && (lastName.dirty || lastName.touched), 'has-success': lastName.valid && (lastName.dirty || lastName.touched)}">
        <label>Last Name</label>
        <input type="text" class="form-control" formControlName="lastName">
    </div>

</fieldset>

<div class="form-group" [ngClass]="{'has-danger': email.invalid && (email.dirty || email.touched), 'has-success': email.valid && (email.dirty || email.touched)}">
    <label>Email</label>
    <input type="email" class="form-control" formControlName="email">
</div>


<div class="form-group" [ngClass]="{'has-danger': password.invalid && (password.dirty || password.touched), 'has-success': password.valid && (password.dirty || password.touched)}">
    <label>Password</label>
    <input type="password" class="form-control" formControlName="password">
</div>


<div class="form-group" [ngClass]="{'has-danger': language.invalid && (language.dirty || language.touched), 'has-success': language.valid && (language.dirty || language.touched)}">
    <label>Language</label>
    <select class="form-control" formControlName="language">
        <option value="">Please select a language</option>
        <option *ngFor="let lang of langs" [value]="lang">{{lang}}</option>
    </select>
</div>

<button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Submit</button>

component.ts

import { Component, OnInit, AfterViewInit, Pipe } from '@angular/core';
import { FormsModule, FormGroup, FormControl, Validators, ReactiveFormsModule, FormBuilder } from '@angular/forms';

export class ModelDrivenFormFormModelValidationComponent implements OnInit {
  langs: string[] = ['English', 'French', 'German'];

  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
      this.createForm();
  }

  createForm() {
      this.myForm = this.fb.group({
          name: this.fb.group({
              firstName: ['', [Validators.required]],
              lastName: ['', [Validators.required]]
          }),
          email: ['', [Validators.required, Validators.pattern('[^ @]*@[^@]*')]],
          password: ['', [Validators.required, Validators.minLength(8)]],
          language: ''
      });
  }

  ngOnInit() {}
}
2

There are 2 answers

1
FAISAL On

The component template is trying to access variable before it has been declared. Use safe navigation operator ?. with all the form fields to avoid that. Example below:

<div class="form-group" [ngClass]="{'has-danger': password?.invalid && (password?.dirty || password?.touched), 'has-success': password?.valid && (password?.dirty || password?.touched)}">
    <label>Password</label>
    <input type="password" class="form-control" formControlName="password">
</div>
1
AT82 On

In reactive forms, you cannot just use for example email to refer to your form control (in contrary to template driven forms where you use a template reference variable).

You need to refer to the actual form control in your template, so for example your email validation could look like this:

[ngClass]="{'has-danger': myForm.controls.email.invalid && ..... }

(It might require the safe navigation operator here too, not sure, you can append that if it throws an error)

in this it's a long path, so you could actually assign this to a variable after building a form, for instance variable email, then you can use the code you have now.

email: FormControl;

createForm() {
  this.myForm = this.fb.group({
      ....
  });

  this.email = this.myForm.controls.email;
}