Build awareness and adoption for your software startup with Circuit.

Angular 17 — Master Conditional statements @if, @else, @switch, @for

Angular 17, a powerful front-end framework, introduces intuitive template control flow blocks that simplify the way developers handle conditional rendering and iterative tasks. In this post, we’ll dive into three essential blocks: @if, @else, and @for.

@if

Similar to JavaScript’s if statement, Angular’s @if control flow block allows developers to conditionally display parts of a template. Consider the following example in a user-controls.component.ts file:

@Component({
  standalone: true,
  selector: ''user-controls'',
  template: `
    @if (isAdmin) {
      <button>Erase database</button>
    }
  `,
})
export class UserControls {
  isAdmin = true;
}

In this instance, the <button> element will only be rendered if the isAdmin property is true. This provides a clean and concise way to manage conditional rendering within templates.

@else

While @if is handy for straightforward conditions, there are situations where providing a fallback is beneficial. This is where the @else block comes into play. In the same user-controls.component.ts file:

@Component({
  standalone: true,
  selector: ''user-controls'',
  template: `
    @if (isAdmin) {
      <button>Erase database</button>
    } @else {
      <p>You are not authorized.</p>
    }
  `,
})
export class UserControls {
  isAdmin = true;
}

Now, if isAdmin is false, Angular will render the <p> element, providing a clear message to users that they are not authorized.

@for

Handling lists of items is a common task in web development. Angular’s @for block simplifies this process by allowing developers to iterate through a list and render repeated elements. Here’s an example in an ingredient-list.component.html file:

<ul>
  @for (ingredient of ingredientList; track ingredient.name) {
    <li>{{ ingredient.quantity }} - {{ ingredient.name }}</li>
  }
</ul>

@Component({
  standalone: true,
  selector: ''ingredient-list'',
  templateUrl: ''./ingredient-list.component.html'',
})
export class IngredientList {
  ingredientList = [
    {name: ''noodles'', quantity: 1},
    {name: ''miso broth'', quantity: 1},
    {name: ''egg'', quantity: 2},
  ];
}

Notice the track keyword, which is crucial for Angular to properly manage updates to the list and ensure accurate reflection in the UI.

Conclusion

In conclusion, Angular’s template control flow blocks — @if, @else, and @for — offer developers powerful tools for handling conditional rendering and list iteration. By understanding these blocks and their nuances, developers can create more dynamic and responsive user interfaces.

❤️ If you like my work, please follow me and subscribe ❤️




Continue Learning