Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show the 'has-error' class on an invalid field in Angular 2

Given:

<div class="form-group" [fieldValidity]="email">
  <label for="email" class="sr-only">Email</label>
  <input [(ngModel)]="model.email" ngControl="email" required>
</div>

And my custom [fieldValidity] directive:

import { Directive, ElementRef, Input } from 'angular2/core';
import {NgControlName} from 'angular2/common';
@Directive({
  selector: '[fieldValidity]'
})
export class FieldValidityDirective {
  private el: HTMLElement;
  @Input('fieldValidity') field: NgControlName;
  constructor(el: ElementRef) { 
    this.el = el.nativeElement;
  }
  private _onValidityChange(value: string) {
    //TODO test field.valid || field.pristine
    if (?) { 
      this.el.classList.remove('has-error');
    } else {
      this.el.classList.add('has-error');
    }
  }
}

How can I get subscribe to the field.valid && field .pristine values to show the error? (I've marked it with 'TODO' below)

like image 693
williamsandonz Avatar asked May 08 '16 16:05

williamsandonz


People also ask

How do you make angular forms dirty?

You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.


1 Answers

An easy way is to use the data-driven approach with the [ngClass] directive as follows

Template:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <div [ngClass]="{'has-error': form.controls['description'].invalid}">
            <input type="text" formControlName="description" class="form-control" required [(ngModel)]="description">
        </div>
    </div>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

Component:

export class FormComponent implements OnInit {

  private form: FormGroup;
  private description: string;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      description: new FormControl('')
    });
  }
}
like image 184
Dominic Avatar answered Sep 24 '22 14:09

Dominic