Tuesday, September 22, 2020

In a previous post I used an example of a label name of a user turns green if the title of the user is a developer. You can take a look here…..

Just like you can apply a single class to an element with a class binding, you can also apply a single style to an element using a style binding.

We’ll just make the font green again if the title of the user is a developer. The code below is going to set the color based on this Ternary statement. If the user title is ‘developer’, then the color will be green, otherwise, it will be this black color.

<div>
  <div [style.color]="user2.title === 'developer' ? 'green' : 'black'">
        Name: {{user2.fullName}}</div>
  <div>Title: {{user2.title}}</div>
</div>

If we want to add more than one style we’ll need to use ngStyle, and to do that inline, it’ll look like this.

<div>
  <div [ngStyle]="{'color': user2.title === 'developer' ? 'green' : 'black',
          'font-weight': user2.title === 'developer' ? 'bold' : 'normal' }">
        Name: {{user2.fullName}}</div>
  <div>Title: {{user2.title}}</div>
</div>

This will work like this, but this is a really convoluted statement to have in a template. So let’s go ahead and break this out into a function. So we’ll replace this with getUserTitleStyle and that will actually help us make our logic a little simpler.

<div>
  <div [ngStyle]="getUserTitleStyle()">
        Name: {{user2.fullName}}</div>
  <div>Title: {{user2.title}}</div>
</div>
getUserTitleStyle(): any {
  if (this.user2 && this.user2.title === 'developer') {
    return {
      color: 'green',
      'font-weight': 'bold'
    };
  }
  return {};
}