nlr_p nlr_p - 1 month ago 5
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>
<div class="col-sm-8">
<button type="submit" >Register now</button>
</div>


My ts,

export class SignUp {

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

onSubmit(form: ISignup): any {

var headers = new Headers();
headers.append('Content-Type', 'application/json')
this.http.post(this.header + 'signup', form, { headers: headers })
.subscribe(
response => {
if (response.json().error_code == 0) {
this.router.navigate(['/login']);
}
else {
console.log(response.json().message);
}
});
}


my css,

.errmsg{
border: 1px solid red;
}

Answer

Just add pristine as shown,

[ngClass]="{errmsg: (!form.controls['lastname'].valid &&
                     !form.controls['lastname'].pristine)}" 
Comments