10 Useful Angular Features You’ve Probably Never Used

10 useful Angular features you might have missed.

Chidume Nnamdi 🔥💻🎵🎮
Bits and Pieces

--

Having spent so much time writing Angular apps, you’re probably convinced you’ve seen it all. To be 100% sure — read on 😃

In addition to our list of Angular features, one tool cannot be overlooked. Bit (Github) makes it very easy to share and collaborate on Angular components across projects. Use it to maintain a consistent UI, speed up development and minimize errors in code.

Example: Angular circle loaders shared on bit.dev

1. 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 @angular/platform-browser. We just inject the Title service in our components and use the setTitle method to set the title.

import { Title } from "@angular/platform-browser"@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.

2. 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 @angular/platform-browser 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.

According to Wikipedia:

Meta elements are tags used in HTML and XHTML documents to provide structured metadata about a Web page. They are part of a web page’s head section. Multiple Meta elements with different attributes can be used on the same page. Meta elements can be used to specify page description, keywords and any other metadata not provided through the other head elements and attributes.

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@angular/platform-browser and inject it in our component.

import { Meta } from "@angular/platform-browser"@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?

3. 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)).

4. 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) {}
navigateTo(url) {
this.location.go(url)
}
goBack() {
location.back()
}
goForward() {
location.forward()
}
}

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 then 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. @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 ) {}
}

7. 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 {}

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 }
]
})

9. 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 {}

10. 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>

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

Conclusion

You feel old yet? 😁😁

Don’t worry, we all have knowledge gaps 😁 there are more to the above list. Angular is huge and complex. Try looking into the Angular sources to see if you can sniff out features never heard of or written about before. I’ll be expecting your finds.

Learn More

--

--

JS | Blockchain dev | Author of “Understanding JavaScript” and “Array Methods in JavaScript” - https://app.gumroad.com/chidumennamdi 📕