karim karim - 25 days ago 11x
TypeScript Question

angular2 interpolation and element (attribute vs property)

after reading angular 2 guide about template expression/ property biding / interpolation, i'm a little confused, here is what confuse me :

Attributes initialize DOM properties and then they are done. Property
values can change; attribute values can't.

For example, when the browser renders ,
it creates a corresponding DOM node with a value property initialized
to "Bob".

When the user enters "Sally" into the input box, the DOM element value
property becomes "Sally". But the HTML value attribute remains
unchanged as we discover if we ask the input element about that
attribute: input.getAttribute('value') // returns "Bob"

The HTML attribute value specifies the initial value; the DOM value
property is the current value.

The disabled attribute is another peculiar example. A button's
disabled property is false by default so the button is enabled. When
we add the disabled attribute, its presence alone initializes the
button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the
button. The value of the attribute is irrelevant, which is why we
cannot enable a button by writing Still

Setting the button's disabled property (say, with an Angular binding)
disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even
when they have the same name. This is so important, we’ll say it

Template binding works with properties and events, not attributes.

but when i write a simple attribute, using interpolation inside attribute string, its work, when i change the
component variable, the change is reflected on the dom


<a href="{{myValue}}">tata</a>
<button (click)="change()">test</button>


import { Component, OnInit } from '@angular/core';

moduleId: module.id,
selector: 'my-test',
templateUrl: 'test.component.html'
export class TestComponent implements OnInit {

myValue : number = 0;

ngOnInit() { }

public change() {
this.myValue = (Math.random() * 10)


In layman's terms, property binding and interpolation are two separate ways to "pass" a component instance variable's value to the template.

You can either do one of the following interchangeably, and the Angular documentation even says that interpolation is slightly favored for readability:

<a href="{{myValue}}">tata</a>
<a [attr.href]="myValue">tata</a>

You couldn't do the following, because this will change a DOM property called href to whatever my myValue is set to, but not the actual attribute:

<a [href]="myValue">tata</a>

because there is no "mapping" from the DOM property href to the attribute href like the documentation describes.