5 Little-Known Angular Tricks That Will Make You a Better Developer
Angular JavaScript framework tips tricks performance maintainability modularity dependency injection pipes ngClass ViewChild

José Matos

25 Apr 2023

5 Little-Known Angular Tricks That Will Make You a Better Developer

    5 Little-Known Angular Tricks That Will Make You a Better Developer

    Angular is one of the most popular JavaScript frameworks, used by millions of developers around the world. Whether you're just starting out or you're an experienced Angular developer, there are always new tips and tricks to learn that will help you improve your work.

    In this article, we'll explore five little-known Angular tricks that will make you a better developer, from improving performance to making your code more modular and maintainable. Let's dive in!

    1. Use trackBy for Better Performance

    If you're working with Angular's ngFor directive, you may have noticed that when the list items change, Angular re-renders all the elements in the list. This can lead to performance issues when displaying large lists of data.

    To improve performance, you can use the trackBy function to tell Angular how to track changes in the list items. Simply pass in a unique identifier for each item in the list, such as an ID or a unique property:

      <ul>
        <li *ngFor="let item of items; trackBy: trackById">
          {{ item.name }}
        </li>
      </ul>
    
      trackById(index: number, item: any) {
        return item.id;
      }
    

    In this example, we use the trackById function to track changes by the item's ID. This helps Angular to only re-render the list items that have actually changed, improving performance.

    2. Use Dependency Injection to Simplify Your Code

    Dependency injection is a powerful feature in Angular that allows you to easily inject services and other dependencies into your components. This can help to simplify your code and make it more modular and maintainable.

    For example, let's say you have a component that needs to make an HTTP request to a backend API. Rather than hard-coding the API URL and HTTP requests in your component, you can create a separate service that handles all API interactions:

      import { Injectable } from '@angular/core';
      import { HttpClient } from '@angular/common/http';
    
      @Injectable({
        providedIn: 'root'
      })
      export class ApiService {
        apiUrl = 'https://my-api.com';
    
        constructor(private http: HttpClient) {}
    
        getItems() {
          return this.http.get(`${this.apiUrl}/items`);
        }
    
        getItemById(id: string) {
          return this.http.get(`${this.apiUrl}/items/${id}`);
        }
      }
    

    Now, in your component, you can easily inject the ApiService and call its methods:

      import { Component } from '@angular/core';
      import { ApiService } from './api.service';
    
      @Component({
        selector: 'app-my-component',
        template: `
          <ul>
            <li *ngFor="let item of items">
              {{ item.name }}
            </li>
          </ul>
        `
      })
      export class MyComponent {
        items: any[] = [];
    
        constructor(private apiService: ApiService) {}
    
        ngOnInit() {
          this.apiService.getItems().subscribe((items) => {
            this.items = items;
          });
        }
      }
    

    Not only does this approach make your code more modular and maintainable, but it also makes it easier to unit test.

    3. Use Pipe Decorators to Transform Data

    Pipes are a powerful feature in Angular that allow you to transform and format data for display in your templates. Angular comes with several built-in pipes, such as the DatePipe and CurrencyPipe, but you can also create your own custom pipes.

    To create a custom pipe, simply create a new class decorated with the @Pipe decorator:

      import { Pipe, PipeTransform } from '@angular/core';
    
      @Pipe({
        name: 'reverse'
      })
      export class ReversePipe implements PipeTransform {
        transform(value: string): string {
          return value.split('').reverse().join('');
        }
      }
    

    Now, in your templates, you can use the pipe by passing in the data to be transformed:

      <p>{{ 'hello world' | reverse }}</p>
    

    This will output "dlrow olleh".

    With pipes, you can easily format dates, numbers, and other data types, as well as create your own custom transformations.

    4. Use ViewChild to Access Child Components

    ViewChild is a decorator in Angular that allows you to access child components and their properties and methods.

    For example, let's say you have a parent component that contains a child component:

      import { Component } from '@angular/core';
      import { ChildComponent } from './child.component';
    
      @Component({
        selector: 'app-parent',
        template: `
          <app-child></app-child>
        `
      })
      export class ParentComponent {
        @ViewChild(ChildComponent) childComponent!: ChildComponent;
    
        ngAfterViewInit() {
          // Access child component properties and methods here
          this.childComponent.doSomething();
        }
      }
    

    In this example, we use the @ViewChild decorator to access the ChildComponent instance and call its doSomething method.

    This allows for easy communication between parent and child components, and can help to simplify your code.

    5. Use ngClass to Dynamically Apply CSS Classes

    ngClass is a directive in Angular that allows you to dynamically apply CSS classes to elements based on conditionals and expressions.

    For example, let's say you want to apply a "selected" class to a list item when it is clicked:

      <ul>
        <li *ngFor="let item of items"
            [ngClass]="{ 'selected': item.selected }"
            (click)="item.selected = !item.selected">
          {{ item.name }}
        </li>
      </ul>
    

    In this example, we use ngClass to apply the "selected" class to the list item when the item.selected property is true. We also toggle this property on click.

    With ngClass, you can dynamically apply CSS classes based on any expression or conditional, allowing for highly flexible and dynamic styling.

    Conclusion

    Angular is a powerful and versatile framework, and there are always new tips and tricks to learn that can help you become a better developer. By using these five little-known Angular tricks, you can improve your performance, simplify your code, and make your applications more modular and maintainable.

    Whether you're a beginner or an experienced Angular developer, these tips and tricks are sure to help you take your skills to the next level.

    © 2023 Designed & Developed by José Matos.