Two-way binding (NgModel)
- Combines property and event binding.
- Automatic synchronization of data happens between the Model and the View.
- Changes are reflected in both component and template.
- Whenever you make changes in the Model, it will be reflected in the View and when you make changes in View, it will be reflected in the Model.
- Syntax, we use special directives (More on directives later!):
[(ngModel)]
Important: FormsModule is Required for Two-Way-Binding!
- For Two-Way-Binding, 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';
<mat-card class="card">
<mat-card-header>
<mat-card-title>{{title}}</mat-card-title>
<mat-card-subtitle>{{likeCount}} Likes</mat-card-subtitle>
</mat-card-header>
<img mat-card-image [src]="imageUrl" alt="shiba">
<mat-card-content>
<p>I am {{'running'}} on port {{port}}</p>
<p [style.fontSize]="size">Server with Id {{server.id}} is {{server.status}}</p>
<p [style]="style">Server status from method: {{getServerStatus()}}</p>
<mat-form-field appearance="fill">
<mat-label>Title</mat-label>
<input matInput [(ngModel)]="title">
</mat-form-field>
</mat-card-content>
<mat-card-actions>
<button mat-button [disabled]="isLikeDisabled" (click)="onLike()">LIKE</button>
<button mat-button [disabled]="isShareDisabled">SHARE</button>
</mat-card-actions>
</mat-card>
Update imports
@Component({
selector: 'app-card',
standalone: true,
imports: [CommonModule, MatCardModule, MatButtonModule, MatFormFieldModule, MatInputModule, FormsModule],
templateUrl: './card.component.html',
styleUrls: ['./card.component.scss']
})