switching the content of a button when it is clicked

I am currently using Angular 7 and I am trying to achieve a functionality where the text on a button changes every time it is clicked, toggling between 'login' and 'logout'.

Below is the code snippet I have been working on:

typescript file:

export class HeaderComponent implements OnInit {

  text: string;

  constructor() {
    this.loadDataFromApi();
  }

  ngOnInit() {
      if (this.token == null) {
        this.text = 'login';
        alert(this.text);

      } else if (this.token) {
         this.token = 'logout';
         alert(this.text);
      }
   }

}

An alert saying undefined is being displayed

html file:

 <button type="button"> {{text}}</button>

Answer №1

It appears that you are using a Comparison Operator (==) instead of the assignment operator (=). Make sure to correct this for your code to function properly. Here is an example of how it should be:

export class HeaderComponent implements OnInit {

  text: any;

  constructor() {}

  ngOnInit() {
    this.loadDataFromApi();
    if (this.token) {
      this.text = 'logout';
      alert(this.text);
    } else {
      this.text = 'login';
      alert(this.text);
    }
  }
}

Note: It is likely that this.loadDataFromApi is an asynchronous function, which means that the code after this call will continue executing without waiting for it to finish. This could result in unexpected behavior, with the alert displaying "login" in most cases.

Answer №2

It is recommended to utilize the assignment operator '=' instead of the comparison operator '=='

this.text ='log in';

 export class HeaderComponent implements OnInit {

    text: any;
    constructor( );

        this.fetchDataFromAPI();
      }
    ngOnInit() {

        if(this.token == null){
          this.text ='login';
          alert(this.text);

        } else if (this.token){
          this.token = 'logout';
          alert(this.text);

        }
    }

Answer №3

Instead of using this.token == null, try using !this.token which checks for both undefined and null values (and is considered the recommended approach).


if(!this.token){
     this.text = 'login';
     alert(this.text);

} else if (this.token){
     this.text== 'logout';
     alert(this.text);
}

Answer №4

Following the else statement, you are updating the value of this.token instead of this.text.

In addition, it is important to remember to use = for assignment, not ==. Here is how you can modify your code:

ngOnInit() {
    if (this.token === null) {
        this.text = 'login';
        alert(this.text);

    } else if (this.token) {
        this.text = 'logout';
        alert(this.text);
    }
}

Note: Have you defined the variable token in your .ts file? It seems to be missing from your provided code.

Answer №5

Essentially, the condition being checked is for the presence of an authorization token; if it exists, the text displays as "logout," otherwise it shows "login."

In your scenario, it appears that this.token is initially undefined.

This is why the alert message indicates undefined.

The current set of conditions will not function properly.

A proper implementation would be:

if (this.token) {//If user is logged in, display 'logout'
    this.text = 'logout';
    alert(this.text);

  } else {//If user is logged out, display 'login'
     this.token == 'logout';
     alert(this.text);
  }

Prior to implementing, ensure you check whether this.token has a value assigned or not.

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

Setting up a personalized configuration entry in environment.js

I am currently working with EmberJS version 2.4.2 and I have a specific requirement to handle custom configuration entries using an environment.js file. var ENV = { APP: { myKey: "defaultValue" } }; While everything works perfectly in development ...

Some sections of the HTML form are failing to load

I'm currently following a tutorial and applying the concepts to a Rails project I had previously started. Here's my main.js: 'use strict'; angular.module('outpostApp').config(function ($stateProvider) { $stateProvider.sta ...

Issue with VUE JS: Score not increasing on click event as desired

Greetings! I've been working on a basic game that increments the score by 1 when the user clicks a button. new Vue({ el: '#MyApp', data: { score: '10', }, methods: { ScoreIncre: function(incre) { this.score ...

The problem arises when trying to use the Jquery click event on buttons that have been generated

I've encountered an issue where I can create components dynamically, but the click event doesn't seem to work on buttons that are dynamically generated. Check out the code snippet below: HTML file: <div class="merge_sections">&l ...

When using React, the page loads and triggers all onClick events simultaneously, but when clicking on a button, no action is taken

I have a strong foundation in HTML and CSS/SASS but I'm just getting started with React. Recently, I encountered an issue that has me stumped. I am trying to highlight a button on the navigation bar based on the current page the user is on. I attemp ...

Using conditional statements to render content based on a certain condition within a

One of my requirements is to dynamically render a React component in the following manner: parent.ts ... <Parent> <Child/> <Parent> ... child.ts ... return (someBoolean && <Component/>) ... While ...

The Tab style in Mobile Angular UI does not get applied correctly when nested within an ng-repear

While working on a tabbed control with mobile-angular-ui (), I encountered an issue when trying to generate the tabs dynamically. Initially, everything looked good with the following code: <ul class="nav nav-tabs" ui-state='activeTab' ui-def ...

"Step-by-step guide on setting up Angularjs ng-model in a Rails environment

Question regarding the utilization of two-way binding in AngularJS and Rails ERB files. Let's say the input value in my .erb file has an initial value like this: example.erb <input type="text" value=" <%= @item.title %> " ng-model ="item.t ...

Switching Between HTML Using Javascript

I am currently working on an app that allows users to easily check the local weather and temperature in either celsius or fahrenheit. However, I've encountered a problem when trying to switch between the two unit types by simply clicking on the temper ...

Avoid triggering the onClick event on multiple submit buttons when the form data is deemed invalid by vee-validate

How can I ensure that the onClick event on a button is only called if certain input fields are valid, using vee-validate ValidationObserver? The validation should apply to individual buttons within a form, rather than the entire form itself, as there are m ...

Hello, I'm looking for assistance with this ReactJS code. Is there anyone who can help me

I am not receiving any output and also not encountering any errors, how can I resolve this issue? import React from 'react' function Array() { function myConcat() { const Villain = ["Harley Quinn", "Brainiac", "Deathstroke"]; cons ...

Issue with Nextjs environmental variables not functioning in JavaScript pages

Currently, I am in the process of developing a Next.js website. Within my JavaScript file, I am fetching data from an API and assigning a token using the .env.local file. However, when attempting to access the .env variable that I've set up, it seems ...

What is the best way to verify a field against a set of string values using Typescript in a NestJS application

I currently have an Enum containing various timezones listed below export enum Timezones { 'Europe/Andorra', 'Asia/Dubai', 'Asia/Kabul', 'America/Antigua' } In the DTO file, I am attempting to valid ...

Encountering a "Missing Access" error on the Discord.js API when trying to register my slash commands

Three years ago, I created a small Discord bot in Typescript that is now present on over 80 guilds. Recently, I made the decision to update it from discord.js-v12.3.1-dev to discord.js-v13.6, while also integrating the popular slash commands feature. Howe ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

Rule in ESLint mandating return type for arrow functions

I currently have the following arrow function within my Angular project: this.httpClient.get('url').subscribe((response)=>{ }); It is important to note that ESLint should detect an error in the above code due to not specifying a return type. ...

The feature module does not have visibility of the Behavioral Subject Value during lazy loading

I am currently working on integrating Shopping Cart Functionality using Angular. Products can be added to the shopping cart either through the dedicated Shopping Cart Page or by clicking the 'ADD TO CART' button on the Product Details page (both ...

My JavaScript if-else statement isn't functioning properly

I'm facing an issue with my if statement not functioning correctly when trying to validate non-numeric inputs for the weight variable upon submission. What could be causing this problem? submitBtn.onclick = function(){ var name = document.get ...

Updating React state via child components

Encountering a strange issue while working on a project, I managed to replicate it in this jsfiddle. The parent component's state seems to be affected when the child component updates its state. Any insights on what might be causing this? Here is the ...

Using either Javascript or jQuery, I want to set a value within an if statement

Can I set a value within an if statement, like this: if (a = jQuery("#user > .mask.fix > .a1").css('display') != 'none'){ b = a + 'hello'; //b=jQuery("#user > .mask.fix > .a1").css('display')+&apos ...