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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With