Can not acces it in the same way as in Angular docs, so must grab the FormGroup instance first and find FormControl instance in there.. I wonder why? This example works:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="myForm.controls.username.invalid" class="alert alert-danger">
username is required
</div>
</div>
While this throws error (difference between these only in *ngIf statement):
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
name="username"
class="form-control"
formControlName="username"
>
<div *ngIf="username.invalid" class="alert alert-danger">
username is required
</div>
</div>
Cannot read property 'invalid' of undefined
form.component:
import {Component} from '@angular/core';
import {FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'sign-up',
templateUrl: 'app/sign-up.component.html'
})
export class SignUpComponent {
myForm = new FormGroup({
username: new FormControl('username', Validators.required),
password: new FormControl('', Validators.required),
});
}