Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the property in property binding [class.selected]?

Tags:

angular

I am learning angular 2 from official hero tutorial.

<ul class="heroes">
      <li *ngFor="let hero of heroes"
        [class.selected]="hero === selectedHero"
        (click)="onSelect(hero)">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
</ul>

I've read the guide about property binding here, but still couldn't understand the following code:

[class.selected]="hero === selectedHero"

Question 1: I know html tag has a class property, but class property does not have a key called "selected". The class property may have a value, which is string "selected". How come this property binding is valid?

Question 2: How does above property binding translated to class="selected" ?

like image 386
Nicolas S.Xu Avatar asked Sep 28 '16 02:09

Nicolas S.Xu


People also ask

What is the property binding?

Property Binding is a one-way data-binding technique. In property binding, we bind a property of a DOM element to a field which is a defined property in our component TypeScript code. Actually, Angular internally converts string interpolation into property binding.

What is property data binding in Angular?

Property binding in Angular helps you set values for properties of HTML elements or directives. Use property binding to do things such as toggle button features, set paths programmatically, and share values between components.

Which syntax is used for property binding?

Property binding uses the [] syntax for data binding.

What is attribute and property binding?

Attribute binding is used to bind an attribute property of a view element. Attribute binding is mainly useful where we don't have any property view with respect to an HTML element attribute. Let's consider an example where we are trying to bind a value to the colspan property of the element.


2 Answers

[class.xxx] and [style.xxx.yy] are special Angular2 binding syntax where

[class.my-class]="expression"

adds (or removes) the CSS class my-class to (or from) the element depending on whether expression results in true or false

[style.width.px]="numExpression"

Sets the width (or any other valid style property)to the value ofnumExpressionand the unitpx` (or any other valid CSS unit)

like image 169
Günter Zöchbauer Avatar answered Nov 02 '22 02:11

Günter Zöchbauer


The difference here is that class is not related to the HTML element, it's an angular binding. You're binding the selected property of Angular's class object to the expression, which will remove or add the property if true/false.

The property binds to class="selected" because when you click the li element, your event handler for click sets the hero, and they match.

like image 35
Sterling Archer Avatar answered Nov 02 '22 02:11

Sterling Archer