add.component.ts
import { Component, OnInit } from '@angular/core';
import { StudentAPIService } from 'src/app/services/student-api.service';
import { Student } from 'src/app/model/student';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
public res: any;
showMsg: boolean = false;
errorMsg: boolean = false;
constructor( private studentAPI: StudentAPIService ) { }
ngOnInit(): void {
}
registration(fm){
this.studentAPI.registerStudent(fm).subscribe(res=>{
if(res === "Email already exist!")
{
this.errorMsg = true;
}
else
{
this.showMsg = true;
}
});
}
}
add.component.html
<div *ngIf="showMsg">
<label for="registration">
<p >
Student Registration Success!
</p>
</label>
</div>
<div *ngIf="errorMsg">
<label for="registration">
<p >
Email already exist! Please register with different email.
</p>
</label>
</div>
In the above code I simply want to show success or error message using *ngIf else
. Here, What happen when I click on button then if email id exist in database then errorMsg
show but when I enter another mail id then errorMsg
not hide and showMsg
are showing above errorMsg
. Now, I want to show one message at a time. So, How can I do this? Please help me.
Thank You
CodePudding user response:
Both messages show when you enter another mail id because you only have logic to set the flags errorMsg
/showMsg
to true while there is no logic to set them to false otherwise.
It will be better if you use only 1 variable to mark the registration successful or not:
add.component.ts
import { Component, OnInit } from '@angular/core';
import { StudentAPIService } from 'src/app/services/student-api.service';
import { Student } from 'src/app/model/student';
@Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {
public res: any;
success: boolean;
constructor( private studentAPI: StudentAPIService ) { }
ngOnInit(): void {
}
registration(fm){
this.studentAPI.registerStudent(fm).subscribe(res=>{
this.success = (res !== "Email already exist!")
});
}
}
add.component.html
<div *ngIf="success">
<label for="registration">
<p >
Student Registration Success!
</p>
</label>
</div>
<div *ngIf="success === false">
<label for="registration">
<p >
Email already exist! Please register with different email.
</p>
</label>
</div>
CodePudding user response:
In your case you can try
if(res === "Email already exist!")
{
this.errorMsg = true;
this.showMsg = false;
}
else
{
this.errorMsg = false;
this.showMsg = true;
}
Not a best practice but it should solve your problem for showing one message at a time