We use cookies to enhance your experience on the site
CodeWorlds

Data Binding - Warrior Communication

Data binding is the way of communication between the component class and the template - like signals between samurai on the battlefield.

Types of Data Binding

1. Interpolation {{ }} - Passing Messages

1<h1>{{ title }}</h1>
2<p>Welcome, {{ userName }}!</p>
3<p>2 + 2 = {{ 2 + 2 }}</p>

2. Property Binding [property] - Binding Properties

1<img [src]="imageUrl" [alt]="imageAlt">
2<button [disabled]="isDisabled">Click</button>
3<div [class.active]="isActive">...</div>
4<input [value]="userName">

3. Event Binding (event) - Listening to Events

1<button (click)="onAttack()">Attack!</button>
2<input (input)="onInput($event)">
3<form (submit)="onSubmit()">...</form>
4<div (mouseenter)="onHover()">Hover over me</div>

4. Two-way Binding [(ngModel)] - Warrior Dialogue

1import { FormsModule } from '@angular/forms';
2
3@Component({
4  imports: [FormsModule],
5  template: \`
6    <input [(ngModel)]="samuraiName">
7    <p>Samurai name: {{ samuraiName }}</p>
8  \`
9})
10export class SamuraiFormComponent {
11  samuraiName = '';
12}

Complete Example

1@Component({
2  selector: 'app-training',
3  standalone: true,
4  imports: [FormsModule],
5  template: \`
6    <div class="training-panel">
7      <h2>{{ trainingName }}</h2>
8
9      <input [(ngModel)]="reps" type="number">
10      <button
11        [disabled]="reps <= 0"
12        (click)="doTraining()">
13        Train!
14      </button>
15
16      <p>Completed repetitions: {{ totalReps }}</p>
17    </div>
18  \`
19})
20export class TrainingComponent {
21  trainingName = 'Sword Training';
22  reps = 10;
23  totalReps = 0;
24
25  doTraining(): void {
26    this.totalReps += this.reps;
27  }
28}
Go to CodeWorlds