Home > Net >  Change login button to logout in angular 13
Change login button to logout in angular 13

Time:11-25

I have a simple list with two buttons. I want to be able to show one or the other depending on whether I'm logged in.

<div>
                <li >
                  <button *ngIf="token === ''" type="button"  (click)="login()">Inicia sesión</button>
                  <button *ngIf="token != ''" type="button"  (click)="logout()">Cerrar sesión</button>
                </li>
              </div>

I tried simply putting the ngIf but it doesn't make it instant, besides that since the log in is in another component I don't really know how to change that from there.

this is my component:

import { Component, ElementRef, ViewChild} from '@angular/core';
import { Router } from '@angular/router';
import { faHamburger } from '@fortawesome/free-solid-svg-icons';
import { UsersService } from './services/user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-app';
  token = this.userService.getToken();

  @ViewChild('clickLogout')clickLogout:ElementRef;

  faHamburger = faHamburger;

  constructor(public userService: UsersService, public router: Router) { }
  
  logout(){
    this.userService.logout();
    
    this.router.navigateByUrl('/login');
  }

  login(){
    this.router.navigateByUrl('/login');
  }
  
}

So as it is, I would need to reload the page every time I need one button or another and I need it to do it instantly when I log in or log out.

CodePudding user response:

try to use that in html,

<div *ngIf="token === ''; else empty">
      <button type="button"  
       (click)="login()">Inicia 
       sesión</button>
    </div>

    <ng-template #empty>
     <button type="button"  
      (click)="logout()">Cerrar sesión</button>
    </ng-template>

in ts call the token in the ngOnInit method and change the route (/login to /logout when you navigate) :

export class AppComponent implements OnInit {
//code...
token=''
ngOnInit(): void {
this.token = this.userService.getToken();}

CodePudding user response:

You should use BehaviorSubject to store the token in the service, add:

public token$ = new BehaviorSubject<string>(null);

then use this.token$.next(valueFromRequest); when you will receive token value and this.token$.next(null); to reset it.

In html code use ngIf in that way:

<button *ngIf="(userService.token$ | async)" type="button" [...]>Logout</button>
<button *ngIf="!(userService.token$ | async)" type="button"[...]>Login</button>
  • Related