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

I noticed that it is possible to bind properties without parentheses. 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>

      

+10


source to share


3 answers


There are several cases where we need to add such html attributes that can be dynamically and an example that outputs json from api request

Case 1 []

known as property binding

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

      

Case 2 {{ }}

known as Interpolation

<my-comp foo="{{data.bar}}"></my-comp>

      



Case 3 Conditional call

<my-comp [attr.foo]="data.bar ? true : false"></my-comp>

      

Both {{}} called Interpolation and [] called as Property Binding mean angular understand that there is a one-way path from data source to view target.

More ... www.codementor.io

+3


source


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

From the docs :



You must omit the parentheses when all of the following is true:

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

You usually initialize attributes this way in standard HTML, and it works just as well for initializing directives and component properties.

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

In general, this means that the value on the right is only interpreted when using parentheses. You can remove the square brackets whenever you see quotes within quotes on the right: [anyStringProperty]="'hello'"

can be changed toanyStringProperty = "hello"

+11


source


Here's a quick summary of the whole situation:

When you use square brackets, the right side is an expression. When you don't use parentheses at all, the right-hand side is a constant.

So this will assign a "constant" string to my-tag input. To achieve the same effect in square brackets: Note the single quote inside. If you do not put a single quote in there, the input to my-tag will be bound to its parent component (where you write this template) or a template variable (for example, for ngFor let-constant) named "constant".

Form here What is the Difference Between Property Binding and Normal Attribute

0


source







All Articles