Angular - 2.15 Binding properties VS string interpolation

In the previous lesson we learned how to use property binding. Now suppose we want to display the current value of allowNewServer. We could use string interpolation: <p>Allow new server? {{ allowNewServer }}</p>. Booleans can be cast to a string, so we get "false" at first and after two seconds we see "true" because we update the property inside a setTimeout. That works, but it is also a perfect example where property binding is just as valid.

Instead of writing the value inside the text node, we can bind the innerText property of the paragraph directly: <p [innerText]="allowNewServer"></p>. The behaviour is identical because the inner text is precisely what sits between the opening and closing tags. So in this very case the two techniques are interchangeable.

When to use which

  • String interpolation: display text inside a template. Use it whenever the goal is to show data in the DOM as content.
  • Property binding: set a property on an HTML element, a directive or a component (e.g. disabled, innerText, src).

It is important not to mix the two syntaxes. Inside the quotes of a property binding you write a TypeScript expression, not interpolation. Writing [disabled]="{{ !allowNewServer }}" is incorrect: the braces are forbidden in that position and will break the application. Property binding already evaluates the expression and assigns the result to the target property. You can call methods, combine boolean operators, do arithmetic - but no braces.

The same logic applies to disabled="{{ !allowNewServer }}": this is a plain HTML attribute receiving a string. Angular treats the value as a literal, so the button will always be disabled because any non-empty string is truthy. The proper Angular syntax is square brackets around the property name: [disabled]="!allowNewServer". Remember the rule: text content uses string interpolation, anything else uses property binding. Once you have built a few features in the course project, this distinction will become second nature.