Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator not working on ngStyle

I am working through a tutorial on Angular4 ngStyle.

I have the following code:

app.component.html

<button
  [ngStyle]="{
    'backgroundColor': canSave ? 'blue': 'gray',
    'color': canSave ? 'white': 'black',
    'fontWeight': canSave ? 'bold': 'normal'
  }"
>
  Save
</button>

app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  canSave   = 'false';
}

Whether canSave is true or false, I get this:

Save button

And the console looks like this:

console

I don't understand why this doesn't work! The ternary operator conditional doesn't not seem to be making any difference. Have I got the syntax wrong? I copied it directly from the tutorial and it seems to work in other situations?

like image 392
Davtho1983 Avatar asked May 21 '26 22:05

Davtho1983


1 Answers

canSave should be a boolean not a string this:

 canSave   = false;

not that

 canSave   = 'false';
like image 91
pezetem Avatar answered May 23 '26 13:05

pezetem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!