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" ?
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.
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.
Property binding uses the [] syntax for data 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.
[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 of
numExpressionand the unit
px` (or any other valid CSS unit)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With