String interpolation
- Used to display dynamic data on HTML template.
- By default, interpolation uses the double curly braces
{{ }}
as delimiters.
Note: Any expression which can be resolved to string in the end can be used by interpolation.
Module allows you to group the components, directives, pipes, and services (more on these later). CommonModule
is one of them provided by Angular which exports all the basic Angular directives and pipes, such as NgIf, NgForOf, DecimalPipe, and so on. We also need to import MatCardModule
provided by @angular/material
to use mat-card
in template.
@Component({
selector: 'app-card',
standalone: true,
imports: [CommonModule, MatCardModule],
templateUrl: './cards.component.html',
styleUrls: ['./cards.component.scss']
})
export class CardComponent {
title: string = 'Data Binding';
port: number = 4200;
}
We have title
and port
being displayed in the view using string interpolation. Both title
and port
are resolved to text when rendered by the view.
<mat-card>
<mat-card-header>
<mat-card-title>{{title}}</mat-card-title>
</mat-card-header>
<mat-card-content>
<p>I am running on port {{port}}</p>
</mat-card-content>
</mat-card>
'running'
is also resolved as text.
<mat-card-content>
<p>I am {{'running'}} on port {{port}}</p>
</mat-card-content>
Little complex! You can even use nested properties to display the value.
server: {id: number, status: string} = {id: 10, status: 'offline'};
<p>Server with Id {{server.id}} is {{server.status}}</p>
Say our server status is returned by the method.
getServerStatus(): string {
return this.server.status;
}
The value returned by getServerStatus
is also resolved as text.
<p>Server status from method: {{getServerStatus()}}</p>