You're probably certain you've seen everything because you've spent so much time creating Angular apps. To be absolutely certain, continue reading.
Aside from our list of Angular features, there is one utility that should not be missed. Bit (Github) makes sharing and collaborating on Angular components across projects a breeze. It may be used to keep a consistent user interface, speed up development, and reduce coding mistakes.
1. The title
The title tag is an HTML element that defines a web page's title. The clickable headline for a particular result is presented in title tags on search engine results pages (SERPs). Usability, SEO, and social sharing all rely on them.
The title in the browser window is determined by Angular apps from the title>.../title> in the index.html. The title does not change when you go between components in Angular.
Did you know that you can change the browser's title using components?
In @angular/platform-browser, Angular offers a Title service. To set the title, we simply inject the Title service into our components and call the setTitle function.
import { Title } from "@angular/platform-browser"
@Component({
...
})
export class LoginComponent implements OnInit {
constructor(private title: Title) {}
ngOnInit() {
title.setTitle("Login")
}
}
The browser's title will be set to "Login" when we visit to the LoginComponent.
We can perform this in all of our project's components so that when they're navigated to, the browser window changes to match the component's title.
2. Metaphor
Our Angular app renders a lot of stuff from the index.html file. Our program will use the meta tags defined in the index.html file. The @angular/platform-browser offers a Meta service that allows us to set meta tags from our components.
This is particularly beneficial when it comes to SEO and sharing the component's page on social media.
Meta elements are tags used in HTML and XHTML texts to offer structured metadata on a Web page, according to Wikipedia. They are found in the head area of a website. On the same page, several Meta elements with different properties can be used. Meta elements are used to define the page description, keywords, and any other metadata that isn't given by the other head elements and attributes.
Meta elements give information about a web page that search engines may utilize to help categorize it properly.
It's pretty simple to utilize; all we have to do is import Meta from @angular/platform-browser and inject it into 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"})
}
}
This allows our BlogComponent to be shown on Facebook, Twitter, and other social media platforms, including titles, photos, and descriptions.
Have you heard of this?
3. Override the interpolation of the template
To show properties in the component, we all use the default template interpolator in our templates.
The beginning and the end are both. If we put a property member between them, the browser DOM will display it.
Do you know that we may use our own symbols to replace the default encapsulation start and end delimiters? It's as simple as specifying it in the Component decorator's interpolation property.
In the AppComponent's template, the interpolation will be "(())" rather than "".
@Component({
interpolation: ["((","))"]
})
export class AppComponent {}
@Component({
template: `
((data))
`,
interpolation: ["((","))"]
})
export class AppComponent {
data: any = "dataVar"
}
"dataVar" will be rendered in lieu of ((data)) during rendering.
4. Geographical location
Using the Location service, we can acquire the URL of the current browser window. Location will either persist to the URL's path or to the URL's hash section, depending on whether LocationStrategy is selected.
We can use Location to travel to a URL, move forward and back in the platform's history, modify the browser's URL, and update the top item on the platform's history stack.
To use the Location service, we inject it from the CommonModule.
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. DOCUMENTATION
We occasionally need to access the document model so that we may do DOM activities in our Angular app.
That is exactly what the DOCUMENT gives. The main rendering context is represented by the DI Token DOCUMENT. This is the DOM Document in a browser. It supports DOM activities that are independent of the environment.
When the Application and Rendering Contexts are not the same, the document may not be available in the Application Context (e.g. when running the application into a Web Worker).
Let's pretend we have the following element in our HTML:
<canvas id="canvas"></canvas>
By injecting DOCUMENT:CANVAS into the HTMLElement, we can obtain hold of the canvas HTMLElement.
@Component({
})
export class CanvasElement {
constructor(@Inject(DOCUMENT) _doc: Document) {}
}
The HTMLElement of canvas may then be obtained by running getElementById ()
@Component({
})
export class CanvasElement {
constructor(@Inject(DOCUMENT) _doc: Document) {}
renderCanvas() {
this._doc.getElementById("canvas")
}
}
We can use ElementRef and template reference to achieve this securely, but you get the point.
Caution: Proceed with caution! Directly interacting with the DOM is hazardous and can expose you to XSS threats.
6. @Attribute decorator
In our Angular project, we mostly employed Component, Module, and Directive decorators.
This Attribute decorator allows us to supply a static string without sacrificing speed by removing the change detection check.
Attribute decorator values are examined once and then never again. They work in the same way as the @Input decorator:
@Component({
...
})
export class BlogComponent {
constructor(@Attribute("type") private type: string ) {}
}
7. HttpInterceptor
This is an extremely strong capability in Angular, similar to a US fighter-interceptor. It intercepts and processes HttpRequests.
By using next, most interceptors will change the incoming request before passing it on to the next interceptor in the chain next.handle(transformedReq).
In rare situations, interceptors may prefer to process a request entirely on their own, rather than delegating it to the rest of the chain. This is acceptable conduct.
HttpInterceptor can be used in the following situations:
- Authentication
- Caching
- Fake backend
- URL translation
- Header modification
@Injectable()
export class MockBackendInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest, next: HttpHandler): Observable> {
...
}
}
Then, in your main module, enter it as follows:
@NgModule({
...
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MockBackendInterceptor,
multi: true
}
]
...
})
export class AppModule {}
8. AppInitializer
We occasionally want a piece of code to execute when our Angular app starts, such as to load certain settings, cache, configurations, or check-ins. This is when the AppInitializer token comes in handy.
APP INITIALIZER: This is a function that is called when an application is first started.
It's simple to use. Let's say we want this runSettings method to be called when our Angular app first launches:
function runSettingsOnInit() {
...
}
We go to our main module, AppModule, and use the NgModule decorator to add it to the providers section:
@NgModule({
providers: [
{ provide: APP_INITIALIZER, useFactory: runSettingsOnInit }
]
})
9. Bootstrap Listener
Angular, like AppInitializer, provides a functionality that allows us to listen in on a component's bootstrapping. The APP BOOTSTRAP LISTENER is what it's called.
For every component that is bootstrapped, any callbacks specified by this token will be called.
Component bootstrapping is important for a variety of reasons. For example, the Router module utilizes it to delete and build components based on route navigation.
We add APP BOOTSTRAP LISTENER to our AppModule's providers section with the callback method to use it:
@NgModule({
{
provide: APP_BOOTSTRAP_LISTENER, multi: true,
useExisting: runOnBootstrap
}
...
})
export class AppModule {}
10. NgPlural
Pluralization is an issue in its own right. In our apps, we must constantly specify grammar appropriately depending on the singular/plural value. Some websites make advantage of (s). Like:
1 component(s) removed
3 component(s) removed
When reading it, the reader has the option of removing (s) or adding (s):)
The NgPlural directive in Angular takes care of this for us.
Based on a numeric number, NgPlural adds/removes DOM sub-trees. Designed with pluralization in mind.
Displays DOM subtrees that match the value of the switch expression, or, if that fails, DOM subtrees that meet the pluralization category of the switch expression.
You must supply a container element with the [ngPlural] attribute set to a switch expression in order to utilize this directive. The expression of inner components with a [ngPluralCase] will be displayed:
<p [ngPlural]="components">
<ng-template ngPluralCase="=1">1 component removed</ng-template>
<ng-template ngPluralCase=">1">{{components}} components removed </ng-template>
</p>
When displaying the amount of "components eliminated," we used the NgPlural directive to remove the (s). It will show the following:
// if 1 component
1 component removed
// if 5 components
5 components removed
Conclusion
Do you think you're becoming old? 😁😁
Don't worry, we all have knowledge gaps, and the list above isn't complete. Angular is a massive and complicated project. Look through the Angular sources to see if you can find any features that have never been mentioned or written about previously. I'll be on the lookout for your discoveries.
0 Comments