Angular: Data Binding
app/servers/servers.component.ts
In template [] means property binding, () means event binding.
String interpolation
This is one way data binding, we are just printing out serverId
and serverStatus
property.
app/servers/servers.component.html
Property Binding
app/servers/servers.component.html
Event Binding
app/servers/servers.component.html
Passing and Using Data with Event Binding
app/servers/servers.component.html
$event
is reserved variable, it contains data which comes from input, so in this case what you type.
Two-Way Data Binding
We combine property and event binding. Important: For Two-Way-Binding to work, you need to enable the ngModel
directive. This is done by adding the FormsModule
to the imports[]
array in the AppModule
.
You then also need to add the import from @angular/forms
in the app.module.ts
file:
import { FormsModule } from '@angular/forms';
Following code will update value of serverName, when you type inside the input. But it will also update value of input if you change value of serverName from somewhere else.
app/servers/servers.component.html
How do you know to which Properties
or Events
of HTML Elements you may bind? You can basically bind to all Properties and Events - a good idea is to console.log()
the element you’re interested in to see which properties and events it offers.
Important: For events, you don’t bind to onclick but only to click (=> (click)).
The MDN (Mozilla Developer Network) offers nice lists of all properties and events of the element you’re interested in. Googling for YOUR_ELEMENT properties or YOUR_ELEMENT events should yield nice results.