Adrian
Adrian

Reputation: 9600

What's the difference between `value="{{todo.title}}"` and `[value]="todo.title"`?

I have been doing a todo app in Angular 2 to graps the concepts... What's the difference between value="{{todo.title}}" and [value]="todo.title"?

Upvotes: 5

Views: 888

Answers (2)

yurzui
yurzui

Reputation: 214095

Let's say we have this data

todo = {
  title: 5
};

1) value="todo.title" - the attribute with name value and value "todo.title" (string)

2) value="{{todo.title}}" - the property with name value and value "5" (always string)

template_parser.ts method _parseAttr enter image description here

Therefore it won't be included as the attribute

enter image description here

3) [value]="todo.title" - the property with name value and value 5 (number)

So difference between those expressions is that the value in the interpolation (value="{{todo.title}}") is always stringified while the value of basic property binding ([value]="todo.title") is passed as is.

Upvotes: 0

bnsd55
bnsd55

Reputation: 318

From Angular doc:

Property binding or interpolation?

We often have a choice between interpolation and property binding. The following binding pairs do the same thing:

<p><img src="{{heroImageUrl}}"> is the <i>interpolated</i> image.</p>
<p><img [src]="heroImageUrl"> is the <i>property bound</i> image.</p>

<p><span>"{{title}}" is the <i>interpolated</i> title.</span></p>
<p>"<span [innerHTML]="title"></span>" is the <i>property bound</i> title.</p>

Interpolation is a convenient alternative for property binding in many cases. In fact, Angular translates those interpolations into the corresponding property bindings before rendering the view.

There is no technical reason to prefer one form to the other. We lean toward readability, which tends to favor interpolation. We suggest establishing coding style rules and choosing the form that both conforms to the rules and feels most natural for the task at hand.

Link

Upvotes: 3

Related Questions