10 More Useful Angular Features You Might Not Have Heard Of

10 More Useful Angular Features You Might Not Have Heard Of

Here I will outline 10 more useful Angular features that you may not know .... for example we may have some components that are used to select items: .... This page should not be accessible to people who have not logged it.

Having spent so much time writing Angular apps, you’re probably convinced you’ve seen it all. To be 100% sure — read 10 More Useful Angular Features You Might Not Have Heard Of

1. 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()
    }
}
2. 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 }
    ]
})
3. 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 ... 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.

4. 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 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 [email protected]/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?

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

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

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

You may also like: 14 Feature and Syntax in Javascript You Might Not Have Heard Of.

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.

Thank you for reading !

AngularJS Development - Why Choose AngularJS For Web Development?

AngularJS Development - Why Choose AngularJS For Web Development?

AngularJS is the most popular framework for web development and nowadays more in demand. We explain in-details why choose AngularJS for web development for your next project?

AngularJS is a web development framework based on open script languages like JavaScript, hypertext markup language and cascading style sheet.
Web development has become an integral part of the marketing world over a period of time. We can't imagine the marketing world without advertisement that is framed virtually or shopping webpage which had made the life of people so much easier.
So, designing a webpage that gives good user experience and has flexible applications are the current requirements of the marketing world.
AngularJS development company has been revolutionary in the web development field. Web developers are constantly utilizing AngularJS to build a vibrant and flexible application.

Here, we would be going through a certain point which would be acknowledging the fact as to why AngularJS should be utilized in web development.
It is one of the most popular web development applications. So, let's glance over certain points. Why?
Certain problems that are tackled by the AngularJS
Imaging, where you are interrupted every time you select a different task on a webpage because the page is refreshed automatically every time. So, this process becomes kinda tedious and most-importantly time-consuming.
This problem is eradicated with the use of AngularJS.
The master language that is utilized by AngularJS as a default language is HTML.
The AngularJS has the ability to support a wide array of functions. A variety of functions can be created on AngularJS without any issues of support. And secondly, it offers certain additional features as well like dependency injection, simple architecture, convenient testing, and parallel development.

1. High Performance
Robustness of web development is what sets this feature apart.
It is powered with a wide horizon of features like filters, data binding, animations, API, scope management, clients, directives, form validation, content sanitation and many more.

2. User Interface
As I have stated earlier the master language that has been set as a default language for AngularJS is HTML.
So, this language creates a good user interface. So, it has automatically sorted one of the biggest hurdles faced during web development which is designed user-friendly flexible apps.

3. Data Binding
Changes made in the modules are quite highlighting in it. So, these features make it more dependable in the market.

4. Filters
They are an integral member or part of any data development features. This added feature helps in creating variations in the web application.
For example, you can use uppercase and lowercase features while present large data to the user.

5. Use Of MVC
AngularJS makes use of features like MVC for the purpose of web application development. MVC stands for the model view controller.
Now, if we break down MVC into three segments that it would be quite easier to understand it. The first segment that is taken into consideration is model designing where all the work related to model development and maintenance is carried out.
Second is the view portion where its sole purpose is only to view the data. And the last segment is the controlling portion which is a linking string between the two components.

6. Testing
It is an important step in any web application development process.
So, the employment of the AngularJS web application, web development has made it quite efficient. It comes with a set of unit test runners that carry out the testing procedure at each and every step of the web development process.
So, it gives you can approximate rough idea as to how the web application is going to perform in the near future.

So, these features set the AngularJS web development application apart from the others. No doubt, it is one of the most demanded web development applications present in the market out there.
Well, if you are a newbie in the web development arena, then you don't have to stress over the fact. There are certain web developers companies that can assist you in the web development process using AngularJS web development.

7. Declarative Code Style
Declarative paradigm is mainly utilized in AngularJS to create patterns while building a web application program.
The main purpose of using declarative code style is to make program code easier, lightweight and decipherable.
Spa features of AngularJS
Validation capabilities are provided along with the AngularJS.
It handles the error-handling issues with its validation capabilities.

8. Easy To Use
With the horde of features provided by the AngularJS, it becomes easy to use.
And because it uses the MVC model in its web development procedure hence it becomes quite easy to use. It minimizes the need to write the code. Secondly, it has an extensible feature as well where HTML can be turned into XML, which makes it more demandable.

Read also: 10 Advantages of AngularJS Development Services for Enterprise

9. Use Of Directives
Whenever you want to make logistics in the web development, you can always opt for this added feature in the AngularJS. It improves code readability.
So, one could always seek out for AngularJS development services to get their work done without any hassle.