One-Way Binding
- Class → HTML Template: The class’s object data is passed to the HTML template.
- HTML → Class: The HTML data is passed back to the class (TS).
Example: One-Way Binding (HTML → Class)
-
HTML
The user inputs data in a textbox, and the value is passed to the class when the button is clicked or the key is pressed:<input type="text" #nameBox placeholder="Enter your name" name="myName"> <input type="button" (keyup)="getName(nameBox.value)" (click)="getName(nameBox.value)" value="Click"> <h2>{{ displayName }}</h2>
-
Component (TS)
ThegetName
method receives the value from the input and updates thedisplayName
:export class TemplateRef implements OnInit { public displayName = ''; getName(value: string) { console.log(value); this.displayName = value; } constructor() {} ngOnInit(): void {} }
Key Points
- Key Events: The
(keyup)
and(click)
events are used to trigger thegetName
method, passing the textbox value to the class. - Interpolation: The
{{ displayName }}
syntax displays the updated value in the HTML template.
Counter Example: Button with Increment (One-Way Binding)
HTML
This example uses a button to increment a number each time it’s clicked, and displays the updated value:
<button (click)="increment()">Increment</button>
<h2>{{ counter }}</h2>
TypeScript (Component)
The counter
variable starts at 0, and the increment()
method increases its value by 1 each time the button is clicked:
export class CounterComponent {
public counter = 0;
increment() {
this.counter++;
}
Key Points:
- Event Binding: The
(click)
event triggers theincrement()
method each time the button is clicked. - Data Binding: The
{{ counter }}
syntax displays the updated counter value in the HTML template.