Ad

Ionic How To Show/hide Content When Logged Out/in

In my ionic app, sign up and log in works and the data is saved in Firebase but I don't how to hide or show a content in home page when user is logged in or out.

In my authentication.service.ts, uid (userID) is set when user is logged in

async signIn(email, password){
try{
  let userData = await this.afAuth.auth.signInWithEmailAndPassword( email, password);
  this.uid = this.afAuth.auth.currentUser.uid;
  return { success: true, uid: this.uid, email: email };
}
catch(error){
  return { success: false, error: error.message };
}
}

home.page.html

<ion-card-content>
sign up here
  <ion-button class="btnSignUp" fill="clear" color="medium" (click)="showSignup()">
      Sign up
  </ion-button>
</ion-card-content>

So I want to use that info in authentication.service.ts and only show that sign up button in my home.page.html when user is NOT logged in.

Ad

Answer

In your home.page.ts do the following:

export class Home implements OnInit{
  currentUser : any;
  showBtn     : boolean = true;
  constructor(public afAuth: AngularFireAuth) {}

  ngOnInit(){
    this.currentUser = this.afAuth.auth.currentUser;
    if(this.currentUser === null){
     this.showBtn = false;
      }
 }

Then in your html:

<ion-card-content *ngIf="showBtn">
sign up here
  <ion-button class="btnSignUp" fill="clear" color="medium" (click)="showSignup()">
  Sign up
 </ion-button>
</ion-card-content>

Here, you first retrieve the currentUser, if the user is not logged in then you can assign showBtn to false and then in the html use ngIf which will show/hide the button.

Ad
source: stackoverflow.com
Ad