uksz
uksz

Reputation: 18719

Difference between inputProperty="data.x" and inputProperty="{{data.x}}"

In my application, I have defined some component, that takes two variables: start and end. I run it in ngFor as follows:

 <template ngFor #exampleData [ngForOf]="data" #idx="index">
        <div>
            <example-component start="exampleData.star" end="exampleData.end" *ngIf="exampleData.start" ></example-component>
        </div>
 </template>

You can see this in the plnkr

As you can see, this code provides example-component with a string of either exampleDate.start or exampleData.end.

It will run as intended when I will add expression into the component like that:

 <template ngFor #exampleData [ngForOf]="data" #idx="index">
        <div>
            <example-component start="{{exampleData.star}}" end="{{exampleData.end}}" *ngIf="exampleData.start" ></example-component>
        </div>
 </template>

My question is: why is that?

Upvotes: 1

Views: 51

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202216

You could leverage property binding for your parameters:

<template ngFor #exampleData [ngForOf]="data" #idx="index">
  <div>
    <example-component [start]="exampleData.star"
                       [end]="exampleData.end" *ngIf="exampleData.start" >
    </example-component>
  </div>
</template>

This way the content provided for these two parameters are evaluated as expressions.

Without [...], they are considered as strings. In the following, the input values for start and end are respectively exampleData.star and exampleData.end:

<example-component start="exampleData.star"
                   end="exampleData.end" *ngIf="exampleData.start" >
</example-component>

Upvotes: 1

Mark Rajcok
Mark Rajcok

Reputation: 364697

Since start is an input property,
start="exampleData.star" is equivalent to (a shorthand for)
start="exampleData.star" [start]=" 'exampleData.star' ".

In other words, it creates HTML attribute start with the value exampleData.star and it creates DOM property start with the value exampleData.star. I don't believe any databinding is created for this.

start="{{exampleData.star}}" interpolates exampleData.star (meaning that it evaluates exampleData.star as an Angular template expression), then it converts the result to a string, then it assigns the string result to DOM property start. It also sets up a databinding, such that the expression exampleData.star is reevaluated each time Angular change detection runs. If the interpolated string value changes, DOM property start is updated.

[start]="exampleData.star" is similar to interpolation, with one significant difference: the template expression exampleData.star is not converted to a string. Whatever value expression exampleData.star evaluates to (e.g., it could be an Object or an Array), that value is assigned to DOM property start.

Upvotes: 0

Related Questions