What Does [Class. Selected] Do?

What Does [Class. Selected] Do?

I am trying to learn angular 6, and I've come across a line of code that I don't think is well explained. It isn't producing any significant changes when being removed from the code, but is in a tutorial that I've been following. Please clear up what the following line of code does in this html file.

[class.selected]="atype === selectedType"

Full html code:

<h2>My Types</h2>
<ul class="types">
  <!-- Create the for loop, and then assign the selected element to the current type. -->
  <li *ngFor="let atype of types"
    [class.selected]="atype === selectedType"
    (click)="onSelect(atype)">
    <span class="badge">{{atype.id}}</span> {{atype.name}}
  </li>
</ul>

<div *ngIf="selectedType">

  <h2>{{selectedType.name | uppercase}} Details</h2>
  <div>
    <span>id: </span>{{selectedType.id}}</div>
  <div>
    <label>name:
      <input [(ngModel)]="selectedType.name" placeholder="name">
    </label>
  </div>

</div>

types refers to an array.

2

1 Answer

[class.selected]="atype === selectedType"

Here, the condition i.e. atype === selectedType will be evaluated first, if it results in true, then the selected css class will be applied to the element in discussion i.e. <li>

This can also be written in another way:

[ngClass]="{'selected': atype === selectedType}"

This would still achieve the same. Same interpretation can be applied to [style.someStyleProperty]="atype === selectedType" and [ngStyle].

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.