Aya Abdelaziz Aya Abdelaziz - 5 months ago 24
TypeScript Question

add div with error in case of wrong validation for username and password angular 4

how can i add div to html code which appear only if the username and password wrong (there is no user or password match this data ) by using angular 4 and typescript

login.component.html :

<form (ngSubmit)="onSignin(f)" #f="ngForm" class="sign">
<div class="login">
<div class="login-screen">
<div class="app-title">
<h1> Login </h1>

<div class="login-form">
<div class="control-group">
<input type="text" class="login-field" placeholder="username" ngModel name="UserName" required>
<span><i class="fa fa-user"></i></span>

<label class="login-field-icon fui-user" for="login-name">
<span style="color: red"> * </span>

<div class="control-group">
<input type="password" class=" login-field" placeholder="password" ngModel name="Password" required>
<span><i class="fa fa-lock" ></i></span>
<label class="login-field-icon fui-lock" for="login-pass">
<span style="color: red"> * </span>

<button class="btn btn-primary btn-large btn-block" [disabled]="!f.valid" (click)="onSignin(f)" >الدخول &nbsp;
<i class="fa fa-sign-in" ></i>


onSignin(form: NgForm){
const UserName = form.value.UserName;
const Password = form.value.Password;



return this.http.get('http://api.###.com/api/###/signin?
.map(res => res.json())
data => {
if (data.Id == 0){
console.log('something error');


any help please ?

Answer Source

You just have to use control.setErrors({invalid: true}); on return inside the subscription.

You might need to move the subscription part from service to component:-

So in service:

signinUser(UserName,Password): Observable<any>{ return this.http.get('http://api.###.com/api/###/signin? username='+UserName+'&password='+Password); }

And in component:

`onSignin(form: NgForm){
    const UserName = form.value.UserName;
    const Password = form.value.Password;

    this.authService.signinUser(UserName,Password).subscribe(response => 
            // Login Success
        errorResponse => {
            // Login Error
            form.controls['UserName'].setErrors({invalid: true});

On the html:

<div [hidden]="!UserName.errors.invalid"> There is no user or password matching this data. </div

Please refer this tutorial

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download