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> <!-- 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>{{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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like