Angular 17 New Control Work Flow(If, else if, else and for)

Angular 17 introduces @for and @if directives, which provide a more powerful and expressive way to handle loops and conditionals in templates. These directives aim to simplify the syntax and enhance performance.

Example: Using @for Directive

The @for directive offers a cleaner and more intuitive way to iterate over collections in templates.


import { Component } from '@angular/core';

@Component({
  selector: 'app-for-example',
  template: `
    <ul>
      @for (let item of items) {
        <li>{{ item.name }}</li>
      }
    </ul>
  `
})
export class ForExampleComponent {
  items = [
    { name: 'Item 1' },
    { name: 'Item 2' },
    { name: 'Item 3' }
  ];
}

Example: Using @if Directive

The @if directive simplifies conditional rendering in templates, making it more readable and maintainable.

import { Component } from '@angular/core';

@Component({
  selector: 'app-if-example',
  template: `
    @if (isLoggedIn) {
      <p>Welcome back, user!</p>
    } else {
      <p>Please log in.</p>
    }
  `
})
export class IfExampleComponent {
  isLoggedIn = false;
}

These new directives provide a more natural way to write conditional and loop logic directly within your templates, improving readability and reducing boilerplate code.

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post