Data binding is the core mechanism that connects your TypeScript logic to the HTML template view.
It ensures that when your data changes, the visual interface updates automatically.
Angular provides several incredibly powerful data binding techniques to handle all application states.
We previously learned about String Interpolation {{ }}, which binds data into text content.
Property Binding allows you to bind data to an element's HTML properties, like an image's src or a button's disabled state.
To use Property Binding, you wrap the target HTML property inside square brackets [ ].
<!-- Binds the 'imageUrl' TypeScript variable to the image src --> <img [src]="imageUrl" alt="Dynamic Image"><!-- Disables the button if 'isFormInvalid' is true --> <button [disabled]="isFormInvalid">Submit</button>
This data flow is strictly one-way: from the TypeScript component down to the HTML DOM.
To capture user actions like clicks, keystrokes, and mouse movements, we use Event Binding.
Event binding flows in the opposite direction: from the HTML DOM up to the TypeScript component.
To use Event Binding, you wrap the target event name inside parentheses ( ).
<!-- Calls the 'onSave()' method when clicked --> <button (click)="onSave()">Save Data</button><!-- Triggers 'onKeyUp()' every time a key is released --> <input type="text" (keyup)="onKeyUp()">
Forms require data to flow in both directions simultaneously.
When a user types in an input box, the data variable must update, and if the data variable changes via logic, the input box must reflect it.
Angular achieves this Two-Way Data Binding using the [(ngModel)] directive.
<!-- The 'username' variable perfectly syncs with this input --> <input type="text" [(ngModel)]="username"><!-- The paragraph will instantly reflect whatever is typed! --> <p>Hello, {{ username }}!</p>
Hint: Developers affectionately call the [()] syntax the "Banana in a Box"!
What is the correct syntax for Property Binding to dynamically disable a button?
Which syntax is affectionately known as the "Banana in a Box" and is used for two-way data binding?