Angular 2: Difference between property binding with and without brackets?

Martijn van den Bergh picture Martijn van den Bergh · Mar 23, 2017 · Viewed 7.2k times · Source

I noticed it's possible to property bind stuff without brackets. What is the difference?

Typescript:

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

@Component( {
    selector: 'my-comp',
    templateUrl: `
    input is {{foo}}
  `

})
export class myComponent {
    @Input() public foo: string;

    constructor() { }
    }

HTML:

Case 1

<my-comp [foo]="bar"></my-comp>

Case 2

<my-comp foo="bar"></my-comp>

Answer

seawave_23 picture seawave_23 · Jan 22, 2018

In general, we can say that we should use bindings without brackets only when we have a fixed string property:

From the docs:

You should omit the brackets when all of the following are true:

  1. The target property accepts a string value.
  2. The string is a fixed value that you can bake into the template.
  3. This initial value never changes.

You routinely initialize attributes this way in standard HTML, and it works just as well for directive and component property initialization.

When setting an element property to a non-string data value, you must use property binding.

All in all, that means that the value on the right only gets interpreted when using brackets. You can remove the brackets whenever you see quotes in quotes on the right: [anyStringProperty]="'hello'" can be changed to anyStringProperty = "hello".

So, property binding without square brackets is possible as long as we also omit the single quotation marks between the double quotation marks when passing down a string.