Angular 6: Cannot read property 'get' of undefined

11,802

Add [formGroup]="form" to your HTML form

<div class="form-group" [formGroup]="form">
   <label for="name">Name</label>
   <input type="text" class="form-control" name="name" formControlName="name">
</div>

Otherwise Angular won't know what to bind the form to, this is similar to formControlName="name" that you need to add for each control. The form-group class is purely used for styling.

Share:
11,802
Ricky
Author by

Ricky

Updated on July 26, 2022

Comments

  • Ricky
    Ricky almost 2 years

    I am practicing with Angular and I have a problem when I try to use "Build-in Validators". I try to pass as a parameter the value of a form field, but when I try to do it I simply have the error that I put in the title "Can not read property 'get' of undefined":

    form.component.ts

    this.form = new FormGroup({
          'name': new FormControl(this.name, [
            Validators.required,
            Validators.minLength(4),
            forbiddenNameValidator(this.name)
          ]),
          'alterEgo': new FormControl(this.alterEgo),
          'power': new FormControl(this.power, Validators.required)
        });
    

    ... more code ...

    get name(): string { return this.form.get('name').value };
    get power(): string { return this.form.get('power').value };
    

    When I try to send the forbiddenNameValidator (this.name) method as a parameter, I get that error.

    form.component.html

    <form [formGroup]="form" (ngSubmit)="Ver()">
    <div class="form-group">
       <label for="name">Name</label>
       <input type="text" class="form-control" name="name" formControlName="name">
    </div>
    </form>
    

    This is the error that I get:

    enter image description here

  • Noumenon
    Noumenon almost 4 years
    I got the same error when I already had [formGroup]="form", but was missing form = this.fb.group(...) in the TypeScript.