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() {}
}
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: