Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: Cannot read property 'get' of undefined

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

like image 601
Ricky Avatar asked Mar 05 '23 20:03

Ricky


1 Answers

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.

like image 151
Andre Lombaard Avatar answered Mar 11 '23 02:03

Andre Lombaard