Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing the text on a button on click

I am working with Angular 7 and I want to change text on button every time It click either it should be login or logout

I am putting my code below:

ts file:

export class HeaderComponent implements OnInit {

  text: any;

  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 undefined is coming

html file:

 <button type="button"> {{text}}</button>
like image 511
Testing Anurag Avatar asked Dec 30 '25 04:12

Testing Anurag


2 Answers

You're using a Comparison Operator(==) instead of the assignment operator(=). Change that and it should work just fine. Something like this:

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);
    }
  }
}

PS: this.loadDataFromApi is most probably async in nature and the code below this call would get executed without waiting for it, thus leading to unexpected behavior. So in most of the cases, you would get login in the alert.

like image 172
SiddAjmera Avatar answered Dec 31 '25 18:12

SiddAjmera


You should use assignment = operator instead of comparison == operator

this.text ='login';

 export class HeaderComponent implements OnInit {

    text: any;
    constructor( );

        this.loadDataFromApi();
      }
    ngOnInit() {

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

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

        }
    }
like image 27
Sivaramakrishnan Avatar answered Dec 31 '25 18:12

Sivaramakrishnan