Angular Features You Probably Didn’t Know About, But Should Definitely Try!
You know, there are some really cool tricks in Angular that not many folks know about. But they can seriously jazz up the stuff you’re making.
Check out a few of these hidden gems you should totally start using:
Custom Template Interpolation:
Think of template interpolation as a way to insert dynamic values into your Angular templates. By default, Angular uses double curly braces ({{ }}
) for this purpose. However, the less-known feature here is that you can create your own custom interpolation symbols. This is helpful when you want to avoid conflicts with other libraries or have special requirements for your project.
For example, you can configure Angular to use {{= =}}
for interpolation like this:
@Component({
selector: 'app-custom-interpolation',
templateUrl: 'custom-interpolation.component.html',
interpolation: ['{{=', '=}}']
})
export class CustomInterpolationComponent {
value = 'Custom Interpolation Example';
}
// custom-interpolation.component.html
{{= value =}}
Output:
Now, in your HTML template, you can use {{= value =}}
instead of the default {{ value }}
for interpolation.
@Attribute Decorator:
The @Attribute decorator is a relatively lesser-known and underutilized feature, yet it has the potential to significantly enhance the performance of your application.
By using the @Attribute decorator, you can retrieve the value of a specific attribute from the hosting element.
For instance, consider a core button component that allows for the specification of a type, which can be either ‘primary’ or ‘secondary’.
export type ButtonType = 'primary' | 'secondary';
@Component({
selector: 'app-button',
template: `
<button [ngClass]="type">
<ng-content></ng-content>
</button>
`
})
export class ButtonComponent {
@Input() type: ButtonType = 'primary';
}
And because it is a static string, we will use it in the template without the brackets.
<app-button type="secondary" (click)="click()">Click</app-button>
There is one downside to this approach. Since we are employing an Input() decorator, Angular will continue to establish a binding for the ‘type’ property and verify it during every change detection cycle, even though this is a static string that doesn’t change.
In this scenario, we can optimize our approach for greater efficiency by utilizing the @Attribute decorator.
import { Component, Attribute } from '@angular/core';
export type ButtonType = 'primary' | 'secondary';
@Component({
selector: 'app-button',
template: `
<button [ngClass]="type">
<ng-content></ng-content>
</button>
`
})
export class ButtonComponent {
constructor(@Attribute('type') public type: ButtonType = 'primary') { }
}
With this modification, Angular will assess it once and subsequently disregard it.
As a rule of thumb, I lean toward employing the @Attribute() approach when the string remains constant and doesn’t undergo any changes.
Connect with me on Medium ✍ : https://medium.com/@Evelyn.Taylor