Back to results for “Templates”
Angular › Components & Templates

How would you conditionally show different content in a component's template?

Intermediate

Answer

Newer versions of Angular provide the at if block, a built in control flow syntax that lets you show or hide content based on a condition directly in your template, replacing the older asterisk ngIf structural directive with a syntax that is closer to regular programming language conditionals.
@Component({
  selector: 'app-greeting',
  template: `
    @if (isLoggedIn) {
      <p>Welcome back</p>
    } @else {
      <p>Please log in</p>
    }
  `
})
export class GreetingComponent {
  isLoggedIn = false;
}
Real-world example A website shows a personalized welcome message for signed in users and a simple login prompt for everyone else, using the new at if block syntax to control which section actually renders.

Common follow-ups: How does the new at if syntax differ in performance from the older asterisk ngIf directive?;What is the at else if syntax used for handling more than two conditions?