Aya Abdelaziz Aya Abdelaziz - 24 days ago 5
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>

<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>
</label>
</div>


<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>
</label>
</div>

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


login.component.ts:

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

this.authService.signinUser(UserName,Password);
}


auth.service.ts:

signinUser(UserName,Password){
return this.http.get('http://api.###.com/api/###/signin?
username='+UserName+'&password='+Password)
.map(res => res.json())
.subscribe(
data => {
if (data.Id == 0){
console.log('error');
console.log('something error');

}
else{
this.router.navigate(['/calendar']);
console.log('Ok');
}}
)
}


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