nlr_p nlr_p - 1 year ago 89
TypeScript Question

How to perform validations with ngClass in angular2

I created a form in which i applied ngclass to show error when form value is not given,nut unfortunately it shows error when the form is loaded for the first time.So by default when the form is loaded my input tag is in-valid ,so it is showing error,i am not sure what to do.Can someone help me pls.

My html,

<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin adminloginform" novalidate>
<label class="col-sm-4 text-right norightpadding">First Name</label>
<div class="input-group" [ngClass]="{errmsg: !form.controls['lastname'].valid }" >
<input type="text" [formControl]="form.controls['lastname']" >
<div class="col-sm-8">
<button type="submit" >Register now</button>

My ts,

export class SignUp {

constructor(public fbld: FormBuilder, http: Http, public config: Config, public router: Router) {
this.http = http;
this.form ={
firstname: ['', Validators.required],
this.header = this.config.header1;

onSubmit(form: ISignup): any {

var headers = new Headers();
headers.append('Content-Type', 'application/json') + 'signup', form, { headers: headers })
response => {
if (response.json().error_code == 0) {
else {

my css,

border: 1px solid red;

Answer Source

Just add pristine as shown,

[ngClass]="{errmsg: (!form.controls['lastname'].valid &&
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download