Im having a problem, more like trouble understanding why a code does/doesn't work while using ngClass directive. I have this css class inside the component.css
.yellow-text {
color: yellow;
}
In the component.html I have this simple paragraph, nameTest is a property from the component which has the value 'Testing'.
<p [ngClass]="{ yellow-text: nameTest === 'Testing' }">ASDASD</p>
This doesn't compile unless I add ' ' in yellow-text.
<p [ngClass]="{ 'yellow-text': nameTest === 'Testing' }">ASDASD</p>
On the other hand, if I make the css class look like this
.yellowtext {
color: yellow;
}
I can use this code.
<p [ngClass]="{ yellowtext: nameTest === 'Testing' }">ASDASD</p>
Why? What am I missing? Sorry for asking this, im probably missing something fundamental.
The reason it does not compile with no quotes, be they single or double, is because ngClass
expects an object, and in Javascript, object keys don't need quotes if they only contain characters, numbers and underscores, if the keys have special characters like -
in your case, you have to put quotes around them. For example
{this is not valid: 'Not OK'}
is not a valid object syntax, to make it valid, you put quotes around the key {'this is now valid': 'OK now'}