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>
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With