In the .
- the from currency code
- the to currency code
- the rate
- a reverse function, which can be called to switch the from and to variables. Reversing the current rate
Using it in a component should be as easy as this:
@Component({
selector: 'my-app',
template: `
<label>From <input [(ngModel)]="fromInput"> </label>
<label>To <input [(ngModel)]="toInput"> </label>
<ng-template exchangeRate [from]="fromInput" [to]="toInput" let-from="from" let-to="to" let-rate="rate" let-refresh="refresh">
<p>Converting from {{from}} to {{to}} the exchange rate is: {{rate}}</p>
<button (click)="refresh()">Reverse</button>
</ng-template>
`,
})
export class AppComponent {
public fromInput = 'USD';
public toInput = 'EUR';
}
Let's look at the overall structure of how our directive might implement this functionality:
@Directive({
selector: '[exchangeRate]',
})
export class ExchangeRateDirective implements OnInit, OnChanges {
// from input which defaults to USD if none is provided
@Input('from')
public from = 'USD';
// to input which defaults to EUR if none is provided
@Input('to')
public to = 'EUR';
// TemplateRef and ViewContainerRef to render to DOM
private template = inject(TemplateRef);
private vcr = inject(ViewContainerRef);
// HttpClient to query API
private http = inject(HttpClient);
// initally we render our template with the default values
public ngOnInit(): void {
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
// whenever an input value changes we query our
// api for the new rate and re-render the template
// given the new input is a 3 letter currency code
public ngOnChanges(changes: SimpleChanges): void {
// get the new from value or keep old
const newFrom = changes.from ? changes.from.currentValue : this.from;
// get the new to value or keep old
const newTo = changes.to ? changes.to.currentValue : this.to;
// over simplified check if inputs are currency code
if (newFrom.length !== 3 || newTo.length !== 3) {
// stop processing changes as definitely not a valid currency code
return;
}
// get new rate and render template to DOM
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
private getExchangeRateFromApiCreateContextRenderTemplate(): void {
...
}
public reverseRate() {
// this is for demonstration purposes only
// since from and to are inputs reassigning those inputs
// might be confusing to the consumer of the directive
const oldFrom = this.from;
this.from = this.to;
this.to = oldFrom;
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
}
First, we take in our from and to inputs with the defaults from the requirements. Then, we inject our dependencies which we need to render our template to the DOM and make API calls to get the newest exchange rate.
// from input which defaults to USD if none is provided
@Input('from')
public from = 'USD';
// to input which defaults to EUR if none is provided
@Input('to')
public to = 'EUR';
// TemplateRef and ViewContainerRef to render to DOM
private template = inject(TemplateRef);
private vcr = inject(ViewContainerRef);
// HttpClient to query API
private http = inject(HttpClient);
On initialization, we get the exchange rate from the API, create the context and render the template.
// initally we render our template with the default values
public ngOnInit(): void {
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
On every subsequent change, we determine if the inputs changed and if they are a currency code. If they did not, we do nothing. If they did, we again get the exchange rate from the API, create the context and render the template.
// whenever an input value changes we query our
// api for the new rate and re-render the template
// given the new input is a 3 letter currency code
public ngOnChanges(changes: SimpleChanges): void {
// get the new from value or keep old
const newFrom = changes.from ? changes.from.currentValue : this.from;
// get the new to value or keep old
const newTo = changes.to ? changes.to.currentValue : this.to;
// over simplified check if inputs are currency code
if (newFrom.length !== 3 || newTo.length !== 3) {
// stop processing changes as definitely not a valid currency code
return;
}
// get new rate and render template to DOM
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
Finally, we define a reverse function that reverses the from and to variable, then gets the reversed rate from the API, creates the context, and renders the template.
public reverseRate() {
// this is for demonstration purposes only
// since from and to are inputs reassigning those inputs
// might be confusing to the consumer of the directive
const oldFrom = this.from;
this.from = this.to;
this.to = oldFrom;
this.getExchangeRateFromApiCreateContextRenderTemplate();
}
Let's take a closer look at the getExchangeRateFromApiCreateContextRenderTemplate method and see how it ties everything together.
private getExchangeRateFromApiCreateContextRenderTemplate(): void {
// 1. we get the new rate based on the from and to currencies and re-render our template
this.http
.get(`https://open.er-api.com/v6/latest/${this.from}`)
.pipe(
// 2. we only care about the immediate response
take(1),
// 3. we extract the rate for the currency
// we convert to
map((response: ExchangeRateResponse) => {
return response?.rates?.[this.to] ?? -1;
})
)
.subscribe((rate) => {
// 4. once the rate arrives, we build the
// context which will be exposed to our template.
const exchangeRateContext = {
// 4.1 current value of our from property
from: this.from,
// 4.2 current value of our to property
to: this.to,
// 4.3 rate returned by api
rate,
// 4.4 function reference to refresh
reverseFn: () => this.reverseRate(),
};
this.vcr.clear();
// 5. we render the template with the new context
this.vcr.createEmbeddedView(this.template, exchangeRateContext);
});
}
- The method uses the HttpClient's get method to request a new rate from the API for our from currency code and
returns an observable of the response. - We ensure we only react to the first value emitted using the
take(1)RxJs operator. - With the
mapoperator, the API response inside of the observable is mapped to the rate for our to currency code. If we cannot find the code, we return a symbolic value of -1. This indicates to users of our directive that something is off so they can display an appropriate message. Of course, this is oversimplified, but I hope you get the idea. - We subscribe to our observable and obtain the rate.
Once the rate is received, we build ourcontextwith the following keys:
from: the current currency code of our directives from property.
to: the current currency code of our directives to property
rate: the exchange rate returned from the API
reverse: a reference to our directives reverseRate function bound to the current execution context with an arrow function.
- We render our template to the DOM and pass the new
context.
Now, we can use our directive in the AppComponent as described above:
@Component({
selector: 'my-app',
template: `
<label>From <input [(ngModel)]="fromInput"> </label>
<label>To <input [(ngModel)]="toInput"> </label>
<ng-template exchangeRate [from]="fromInput" [to]="toInput" let-from="from" let-to="to" let-rate="rate" let-refresh="refresh">
<p>Converting from {{from}} to {{to}} the exchange rate is: {{rate}}</p>
<button (click)="refresh()">Reverse</button>
</ng-template>
`,
})
export class AppComponent {
public fromInput = 'USD';
public toInput = 'EUR';
}
And see our code in action:
One step at a time
There are a lot of ways to improve our directive such as improving performance by avoiding re-renders using observables for our exposed variables and strict type checking for our context in the ng-template.
However, these are topics for another post. If you are interested in how to strictly type your context exposed to templates Thomas Laforge wrote this great article covering everything you need to know. I highly recommend you read it!
Let's be proud of ourselves today. We took another step to master structural directives in Angular by understanding the key concept of the context. Let's take some time to digest all this new information and get ready to learn everything about the structural directive micro syntax. The magic that brings us back our asterisk.
SOCIAL SHARE CARD GENERATOR