Sergey Mell
Sergey Mell

Reputation: 8040

Angular Input binding performance

Is there any difference in performance between using input binding with and without brackets for static data? I mean

<my-component [customTitle]="'Hello World'"></my-component>

vs

<my-component customTitle="Hello World"></my-component>

I appreciate it if anybody shares some useful articles related to this topic

Upvotes: 2

Views: 629

Answers (2)

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

To bind to an element's property, enclose it in square brackets, [], which identifies the property as a target property. A target property is the DOM property to which you want to assign a value. For example, the target property in the following code is the image element's src property.

<img [src]="itemImageUrl">

In most cases, the target name is the name of a property, even when it appears to be the name of an attribute. In this example, src is the name of the element property.

The brackets, [], cause Angular to evaluate the right-hand side of the assignment as a dynamic expression. Without the brackets, Angular treats the right-hand side as a string literal and sets the property to that static value. This is known as Property binding.

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.

Is there any difference in performance between using input binding with and without brackets for static data?

It is depend on when to use what. There is no such visible performance difference in these, but definitely one executes the expression. If you have static data use without brackets recommended by angular docs.

Note: if you disable default change detection strategy to OnPush, you can save a lot of performance issues.

You can check here when to use data binding, property binding, interpolation in angular.

Upvotes: 0

Eliseo
Eliseo

Reputation: 57909

If you use static data, use Attribute decorator

In constructor

constructor(@Attribute('customTitle') private customTitle: string) {}

In you want to use in html, use public instead of private, if you're planning the component can to has or not use @Optional

constructor(@Optional() @Attribute('customTitle') public customTitle: string) {
   //and you can use, e.g.
   if (!this.customTitle)
       this.title="a title by defect"
}

//or in your .html, e.g.
<div *ngIf="!customTitle">Title by defect</div>
{{customTitle}}

You can check this entry of Netanel Basal about it

Upvotes: 2

Related Questions