12 Useful Angular Features for Developer

12 Useful Angular Features for Developer

Angular is an enormous framework, and most of us ever use only a fraction of it. But hiding in plain site are many useful features that can make your life simpler. In this article I am going to cover 12 useful Angular features that you may have not heard of.

Angular is an enormous framework, and most of us ever use only a fraction of it. But hiding in plain site are many useful features that can make your life simpler. In this article I am going to cover 12 useful Angular features that you may have not heard of.

1. Override Template interpolation

We all use the default template interpolator {{}} in our templates to display properties in the component. The start is {{ and the end is }}. If we place a property member in between them it will be rendered on browser DOM.

Do you know that we can override the default encapsulation start and end delimiters with our own symbols? It’s simple, specify that in the interpolation property in the Component decorator.

@Component({
    interpolation: ["((","))"]
})
export class AppComponent {}

The interpolation to use in the AppComponent’s template will be "(())" no longer "{{}}".

@Component({
    template: `
        <div>
            ((data))
        </div>
    `,
    interpolation: ["((","))"]
})
export class AppComponent {
    data: any = "dataVar"
}

On rendering "dataVar" will be rendered in place of ((data)).

2. JSON Pipe

The JSON pipe is incredibly useful, especially when debugging. It allows you to display an object in string for within your view. This can often be an easier alternative to having breakpoints and debugger statements.

Simply add the JSON pipe to the object you wish to display:

<p>{{ myObj | json }}</p>

JsonPipe Documentation: https://angular.io/api/common/JsonPipe

3. Meta

Our Angular app renders things that are mostly from the index.html. The meta tags our app will have is the one set in the index.html. Angular has a Meta service in the CommonModule that enables us to set meta tags from our components.

This is very useful when looking in terms of SEO and sharing the page held by component to social media.

Meta elements provide information about the web page, which can be used by search engines to help categorize the page correctly.

It is very easy to use, just import Meta from CommonModule and inject it in our component.


import { Meta } from "@angular/common"
@Component({
    ...
})
export class BlogComponent implements OnInit {
    constructor(private meta: Meta) {}
    ngOnInit() {
        meta.updateTag({name: "title", content: ""})
        meta.updateTag({name: "description", content: "Lorem ipsum dolor"})
        meta.updateTag({name: "image", content: "./assets/blog-image.jpg"})
        meta.updateTag({name: "site", content: "My Site"})
    }
}

With this our BlogComponent can be rendered on Facebook, Twitter, etc describing our component, providing titles, images, and descriptions. Heard of this too?

4. Title

A title tag is an HTML element that specifies the title of a web page. Title tags are displayed on search engine results pages (SERPs) as the clickable headline for a given result. They’re crucial for usability, SEO, and social sharing.

Angular apps set the title in the browser window from the <title>...</title> in the index.html. Navigating to components in Angular doesn't change the title.

Did you know, you can set the title of the browser from components?

Angular has a Title service in CommonModule. We just inject the Title service in our components and use the setTitle method to set the title.

import { Title } from "@angular/common"
@Component({
    ...
})
export class LoginComponent implements OnInit {
    constructor(private title: Title) {}
    ngOnInit() {
        title.setTitle("Login")
    }
}

When we navigate to the LoginComponent the title of the browser will be set to “Login”

We can repeat that in all the components in our project so that when they are navigated to, the browser window will be changed to reflect the title of the component.

5. DOCUMENT

Sometimes we want to get the document model so we can perform DOM operations from our Angular app.

The DOCUMENT provides just that. DOCUMENT is a DI Token representing the main rendering context. In a browser, this is the DOM Document. It provides DOM operations in an environment-agnostic way.

Note: Document might not be available in the Application Context when Application and Rendering Contexts are not the same (e.g. when running the application into a Web Worker).

Let’s say we have an element in our html:

<canvas id="canvas"></canvas>

We can get hold of the canvas HTMLElement by injecting DOCUMENT:

@Component({
})
export class CanvasElement {
    constructor(@Inject(DOCUMENT) _doc: Document) {}
}

We can the, get the HTMLElement of canvas by calling getElementById()


@Component({
})
export class CanvasElement {
    constructor(@Inject(DOCUMENT) _doc: Document) {}
    renderCanvas() {
        this._doc.getElementById("canvas")
    }
}

We can safely do this using ElementRef and template reference but you got the idea.

Warning: Tread carefully! Interacting with the DOM directly is dangerous and can introduce XSS risks.

6. Location

We can get the URL of the current browser window using Location service. Depending on which LocationStrategy is used, Location will either persist to the URL's path or the URL's hash segment.

With Location, we can go to a URL, navigate forward in the platform’s history, navigate back in the platform’s history, change the browsers URL, replace the top item on the platform’s history stack.

We inject the Location service from the CommonModule to use it.


import { Location } from "@angular/common"
@Component({
    ...
})
export class AppComponent {
    constructor(private location: Location) {}
    navigatTo(url) {
        this.location.go(url)
    }
    goBack() {
        location.back()
    }
    goForward() {
        location.forward()
    }
}

7. @Attribute decorator

We have used mainly: Component, Module, Directive decorators in our Angular app.

We have this Attribute decorator, which enables us to pass static string without a cost at performance by eliminating change detection check on it.

The values of Attribute decorator are checked once and never checked again. They are used similarly to @Input decorator:


@Component({
    ...
})
export class BlogComponent {
    constructor(@Attribute("type") private type: string ) {}
}

8. AppInitializer

We do sometimes want a piece of code to be run when our Angular app is starting, maybe load some settings, load cache, load configurations or do some check-ins. The AppInitialzer token helps out with that.

APP_INITIALIZER: A function that will be executed when an application is initialized.

It is easy to use. Let’s we want this runSettings function to be executed on our Angular app startup:


function runSettingsOnInit() {
    ...
}

We go to our main module, AppModule and add it to providers section in its NgModule decorator:

@NgModule({
    providers: [
        { provide: APP_INITIALIZER, useFactory: runSettingsOnInit }
    ]
})

@NgModule({
    providers: [
        { provide: APP_INITIALIZER, useFactory: runSettingsOnInit }
    ]
})

9. HttpInterceptor

Much like a US fighter-interceptor, this is a very powerful feature in Angular. It intercepts HttpRequest and handles them.

Most interceptors will transform the outgoing request before passing it to the next interceptor in the chain, by calling next.handle(transformedReq).

In rare cases, interceptors may wish to completely handle a request themselves, and not delegate to the remainder of the chain. This behavior is allowed.

HttpInterceptor can be used in:

  • Authentication
  • Caching
  • Fake backend
  • URL transformation
  • Modifying headers

It is simple to use, first create a service and implement the HttpInterceptor interface.


@Injectable()
export class MockBackendInterceptor implements HttpInterceptor {
    constructor() {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        ...
    }
}

Then, insert it in your main module:


@NgModule({
    ...
    providers: [
        {
            provide: HTTP_INTERCEPTORS,
            useClass: MockBackendInterceptor,
            multi: true
        }
    ]
    ...
})
export class AppModule {}

10. Bootstrap Listener

Just like AppInitializer, Angular has a feature that enables us to listen on when a component is being bootstrapped. It is the APP_BOOTSTRAP_LISTENER.

All callbacks provided via this token will be called for every component that is bootstrapped.

We have many reasons to listen to components bootstrapping, for example, the Router module uses it to destroy and create components based on the route navigation.

To use APP_BOOTSTRAP_LISTENER, we add it to the providers section in our AppModule with the callback function:


@NgModule({
    {
        provide: APP_BOOTSTRAP_LISTENER, multi: true, 
        useExisting: runOnBootstrap
    }
    ...
})
export class AppModule {}

11. NgPlural

Pluralization is a problem in its sphere. We need to always correctly define grammar in our apps based on the singular/plural value. Some websites use the (s). Like:

1 component(s) removed
3 component(s) removed

:) It is up to the reader to remove (s) or add (s) when reading it :)

Angular deals with this issue for us in its NgPlural directive.

NgPlural adds/removes DOM sub-trees based on a numeric value. Tailored for pluralization.

Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees that match the switch expression’s pluralization category.

To use this directive you must provide a container element that sets the [ngPlural] attribute to a switch expression. Inner elements with a [ngPluralCase] will display based on their expression:


<p [ngPlural]="components">
    <ng-template ngPluralCase="=1">1 component removed</ng-template>    
    <ng-template ngPluralCase=">1">{{components}} components removed </ng-template>    
</p>

<p [ngPlural]="components">
    <ng-template ngPluralCase="=1">1 component removed</ng-template>    
    <ng-template ngPluralCase=">1">{{components}} components removed </ng-template>    
</p>

See, we have used NgPlural directive to remove the (s) when displaying number of "components removed". It will display:

// if 1 component
1 component removed
// if 5 components
5 components removed

12. Decimal Pipe

This is a very simple pipe is designed for formatting numbers. It can be very useful to limit the number of digits to be displayed after the decimal point, however it can also be used if you would simply like to have you number presented in a more readable fashion, with commas between every thousand, so 1000 would become 1,000.

One additional feature that is related to this pipe, is the formatNumberfunction that is part of @angular/common that allows you to apply the same formatting programmatically rather than having to do this in your view with a pipe.

<p>Your number is: {{ value | number }}</p>

So there you have it! There is my list of 12 things you my not have known Angular had available to use. Hopefully you will find a use for some of them!

Thanks for reading !

angular developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Install Angular - Angular Environment Setup Process

Install Angular in easy step by step process. Firstly Install Node.js & npm, then Install Angular CLI, Create workspace and Deploy your App.

Offshore Software Development - Best Practices

To make the most out of the benefits of offshore software development, you should understand the crucial factors that affect offshore development.

Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

Angular Development Company | Skenix Infotech

Skenix Infotech is a top-notch Angular development company providing customized AngularJS development services. Hire reliable & expert Angular developers from us.