Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does [class.selected] do?

Tags:

html

angular

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.

like image 936
Brandon Finley Avatar asked Oct 19 '25 01:10

Brandon Finley


1 Answers

[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.

like image 199
rgantla Avatar answered Oct 22 '25 05:10

rgantla