Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular property binding [duplicate]

Angular has different ways to data bind properties:

<img src="{{ myProperty }}">
<img bind-src="myProperty ">
<img [src]="myProperty">

Is there a correct way to bind component properties to the view? What is the difference between these three ways, when and why should I use each one?

like image 605
Vinicius Brasil Avatar asked Sep 22 '17 15:09

Vinicius Brasil


2 Answers

Interpolation and Property binding are virtually the same, and bind-src is just an alternate way that is wordy and not often used.

the difference:

interpolation "injects" the value into the html, so when you say value="{{ hello }}" Angular is inserting your variable between the brackets.

property binding allows Angular to directly access the elements property in the html. this is a deeper access. When you say [value]="hello" Angular is grabbing the value property of the element, and setting your variable as that property's value.

event binding allows you to use events such as a click to trigger functions. these bindings use parenthesis for example (click)="myFunction($event)". this will call the myFunction() method on defined in your .ts file. the parenthesis around '(click)' bind the function to the dom event.$event is a keyword passing the event object to the function. you could also pass a string with single quotes, or even a variable with interpolation.

Two way (data) binding allows you to have an event combined with a property binding. For example

<input [(ngModel)]="username">
<p>Hello {{username}}!</p>

will allow you to have an input and display the value at the same time. learn more here

Lastly when to use interpolation and when to use data-binding. This is usually a formality, typically when using a smart component and dumb (presentation) component, you would bind to the html with property binding because of readability, and because it is shall I say, "more secure" to bind to a property in that case. If you have simple values, then maybe interpolation is your friend. It all comes down to readability, best practice, and preference.

like image 136
FussinHussin Avatar answered Oct 23 '22 14:10

FussinHussin


See property binding

and binding or interpolation

Interpolation is a convenient alternative to property binding in many cases.

When rendering data values as strings, there is no technical reason to prefer one form to the other. You lean toward readability, which tends to favor interpolation. You suggest establishing coding style rules and choosing the form that both conforms to the rules and feels most natural for the task at hand.

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

like image 1
Moema Avatar answered Oct 23 '22 14:10

Moema