Template expressions and statements let you show data and respond to user actions in Angular templates. They connect your app's logic with what users see and do.
0
0
Template expressions and statements in Angular
Introduction
Displaying user names or dynamic text on a webpage.
Updating a counter when a button is clicked.
Showing or hiding parts of the page based on conditions.
Running a function when a user types in a form.
Changing styles or classes based on data.
Syntax
Angular
<div>{{ expression }}</div>
<button (click)="statement">Click me</button>Expressions go inside double curly braces {{ }} and show values.
Statements go inside parentheses with event names, like (click), and run code when events happen.
Examples
Shows the value of
userName from the component.Angular
<p>{{ userName }}</p>Runs the
increment() method when the button is clicked.Angular
<button (click)="increment()">Add</button>Shows the value of
count plus one.Angular
<p>{{ count + 1 }}</p>Calls
updateName with the typed text whenever the user types.Angular
<input (input)="updateName($event.target.value)">Sample Program
This component shows a greeting with the user's name and a count number. The count increases when the button is clicked. The name updates as the user types in the input box.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <h1>Hello, {{ userName }}!</h1> <p>Count: {{ count }}</p> <button (click)="increment()">Increase</button> <input (input)="updateName($event.target.value)" placeholder="Enter your name"> ` }) export class CounterComponent { userName = 'Friend'; count = 0; increment() { this.count++; } updateName(name: string) { this.userName = name || 'Friend'; } }
OutputSuccess
Important Notes
Template expressions are simple and should not contain complex logic or assignments.
Statements can call methods or update data but should be fast to keep the UI responsive.
Use $event to access event details inside statements.
Summary
Template expressions show data inside {{ }}.
Template statements run code on events like clicks using (event).
They help make your app interactive and dynamic.