ISAAC POULTON ISAAC POULTON - 2 months ago 10
HTML Question

Angular 2 referring to controls for validation messages

I'm trying to get validation messages to work in Angular 2. There have been so many changes to Angular 2 that there doesn't seem to be an elegant solution on the internet (so please don't mark this as duplicate).

Currently, to show validation messages on my model driven form I'm doing this:

<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" formControlName="name">
<div class="text-warn" *ngIf="!addUserForm.controls.name.pristine && !addUserForm.controls.name.valid">
Please enter a name
</div>
</div>


The formbuilder of my component looks like this:

ngOnInit() {
this.addUserForm = this.fb.group({
name: ['', [Validators.required]],
email: ['', [Validators.compose([EmailValidators.normal(), Validators.required])]],
phone: ['', [Validators.compose([UniversalValidators.isNumber(), Validators.required])]],
address: this.fb.group({
addr1: ['', [Validators.required]],
addr2: [''],
addr3: [''],
city: ['', [Validators.required]],
zip: ['', [Validators.required]],
})
});
}


I remember that I used to be able to get validation messages to display by using a simple
*ngIf="!name.valid"
but now I can't seem to get it working without referring to the whole form group (
*ngIf="!addUserForm.controls.name.valid"
). If I do it the short way I get an error message about
valid
being undefined (presumably because I can't refer to the control directly, for some reason).

There must be a less verbose way to do this.

Answer

I remember that I used to be able to get validation messages to display by using a simple *ngIf="!name.valid" ...

I think it is possible with Template driven forms not with Reactive forms/Model driven forms.

I also think, with Reactive forms/Model driven forms, this is the only way because you have to tell angular2 that with which formGroup, a particular control is attached to...