Update the login button to display as logout in Angular 13

I want to display a simple list with two buttons, where one button is shown if I am logged in and the other if I am not.

<div>
                <li class="nav-item">
                  <button *ngIf="token === ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="login()">Log In</button>
                  <button *ngIf="token != ''" type="button" class="btn btn-dark btn-lg fs-4" (click)="logout()">Log Out</button>
                </li>
              </div>

Although initially I tried using ngIf for conditional rendering, it does not update instantly upon login or logout. In addition, as the login functionality is in another component, I am unsure of how to trigger the change from there.

Below is the code for 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');
  }
  
}

Currently, the page needs to be reloaded each time to toggle between the two buttons. I require an instant update upon login or logout without needing to refresh the page.

Answer №1

Give this a try in HTML format:

<div *ngIf="token === ''; else empty">
      <button type="button" class="btn btn-dark btn-lg fs-4" 
       (click)="login()">Log In</button>
    </div>

    <ng-template #empty>
     <button type="button" class="btn btn-dark btn-lg fs-4" 
      (click)="logout()">Log Out</button>
    </ng-template>

In your TypeScript file, access the token in the ngOnInit method and update the route (/login to /logout when navigating):

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

Answer №2

One effective strategy is to utilize BehaviorSubject for storing the token within the service. Begin by implementing:

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

Upon receiving the token value, invoke

this.token$.next(valueFromRequest);
. To reset the token, use this.token$.next(null);.

When integrating this in HTML code, apply ngIf as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The radio button is displaying the text 'on' instead of its designated value

function perform_global(tablecounter) { for (index = 1; index <= 2; ++index) { var dnsname = "dns_name"+index; oRadio = document.getElementsByName(dnsname); alert (" radio ID " + dnsname + " " + index + "length " + oRadio.leng ...

Generating objects with Sails.js - diving into nested creations

Currently, I have a controller set up to handle an API call /task/:id/start. Within this controller method, the first step is to validate if the Task with the specified ID is valid. If it is determined to be valid, then I need to proceed by creating two ot ...

Submitting an AJAX form did not result in any data being returned

Input Form: <form action="" id="register" method="post"> <input type="text" placeholder="Enter your first name"> <input type="text" placeholder="Enter your last name"> <input type="text" placeholder="<a href="/cdn-cgi/l ...

Using Javascript, retrieve a custom attribute specific to a checkbox option

How can I access the custom attribute "mem_name" value? <input class="messageCheckbox" type="checkbox" value="3" mem_name='ABC' name="checkmember" > <input class="messageCheckbox" type="checkbox" value="1" mem_name='PQR' name ...

Modify the outDir of the compiled code in NativeScript

I find it frustrating that the js files are always generated next to my ts/ng files. It's really annoying, so I decided to move the compiled/transpiled js files outside of the app directory, just like in any typical Angular app. This is what I did: ...

Utilizing Angular resolver to inject the router functionality

In my Angular (v13) application, I have defined a resolver to interact with a Wordpress backend. The purpose of this resolver is to determine the post type and ID from Wordpress when a user accesses a URL, and then route accordingly (to a post list, single ...

Ionic: Implementing a clear text field function when the ion-back-button is clicked

So I've created a feature where users can scan product barcodes using BarcodeScanner. Once the barcode is scanned, the product ID appears in a text field and is then sent to another page where an API call is made to display product details. On this pr ...

Looking to retrieve just your Twitter follower count using JavaScript and the Twitter API V1.1?

I am trying to retrieve my Twitter follower count using JavaScript/jQuery in the script.js file and then passing that value to the index.html file for display on a local HTML web page. I will not be hosting these files online. I have spent weeks searching ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

Transmit an array of JavaScript objects using Email

Within the code layout provided with this post, I have executed various operations in JavaScript which resulted in an array of objects named MyObjects. Each object within MyObjects contains properties for Name and Phone, structured as follows: MyObject ...

Building a series of radio buttons using *ngFor [Angular2]

I am facing an issue with generating a dynamic number of radio buttons based on the length of an Array Of Objects (example: enum_details): Here is the code snippet I have attempted: <div *ngFor="let enum of enum_details"> <label for="enum_answ ...

Generate a new array of objects by cloning an existing array of objects with placeholder values

I am looking to transform an array of objects into another array of objects in order to generate a graph. Below is the array I am using to determine the position of each object within the new object. let uniqueSkills = ['Using', 'Analyzing ...

Encountering Main.js Path Error in Asp.net Core and Angular 2 Integration

I am currently in the process of developing an asp.net core application with Angular 2 and utilizing Angular Quickstart for assistance. With the flexibility provided by Asp.Net core application to use wwwroot as a folder, I have consolidated all dependenc ...

Increase scrolling speed? - Background abruptly moves after scroll

I'm facing a minor issue. I want to create a parallax background effect similar to what can be seen on nikebetterworld.com. In my initial attempt, I managed to achieve some functionality, but I believe it can be improved. As I scroll, the background p ...

Enable a VueJS directive on-the-fly from a separate directive

My goal is to simplify the process of binding a form control to vuejs by creating a directive that handles all necessary events for tracking changes in a form field. Rather than manually adding multiple event listeners like this: <input type="text" na ...

Can you explain the concept of the "Regular Expression Denial of Service vulnerability"?

After recently setting up nodejs on a server, I ran a basic npm install command and received multiple messages like the following: $ npm install npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55383c3b3c3834 ...

connect and disconnect functions

I am working on a project that involves 3 buttons - btn 1, 2, and 3 - each with its own assigned function. The goal is to have button 1 initially set to function 1 by default. However, when button 2 is pressed, the function of button 1 should switch to f ...

redux form has encountered an error: the element type provided is not valid, a string is expected for built-in components

While working on my stepper code, I attempted to add a radio button. However, this addition resulted in the following error. I referenced this example before implementing it. Despite that, I am still encountering errors. Could you please advise me on how ...

Guide to setting a generic key restriction on a function parameter

Today, I decided to have some coding fun and try creating a generic pushUnique function. This function is designed to check if a new object being added to an array is unique based on a key, and then push it if it meets the criteria. At this point, all I h ...

What is the best way to deactivate ng-repeat using a button in AngularJS?

How can I disable the apply button once it has been clicked by the user in a list of stores based on services? I am using ng-repeat to display the listing. Additionally, how can I write an apply function to disable a particular service once it has been app ...