Typing the Context Object in Angular Structural Directives
In this article, we’ll learn how we can type the context
object when creating custom structural directives. Let’s create a structural directive that provides the same functionality as the async
pipe. It’ll get an observable, subscribes to it, and expose the next
value via context
:
We’ve created a structural directive that does nothing 😄. We skip the implementation because it’s not relevant to this article. You can learn about it in one of my previous articles.
Now let’s use it in the template and see that its context
is typed as any
:
To fix this issue and add typing to our context
, we can add a special static property to our class named ngTemplateContextGuard
:
Now let’s see what’s changed in our template:
Great, our context
has the correct type 😋
The way it works is that Angular will compile our template and create Type Check Blocks. These blocks are native typescript code that’s responsible for type checking. In our case, Angular leverages a typescript feature called type guards to infer the context
type.
To let you feel what it looks like, I’ve created a cleaner version of the TSB
output for the AppComponent
template:
You can examine the code by yourself by setting a debugger in the source code at this line:
Angular will feed this output to the Typescript compiler and let it run diagnostics on it. It’ll also add source maps so that it can point to the correct place in our template 💪
🚀 In Case You Missed It
Here are a few of my open source projects:
- Akita: State Management Tailored-Made for JS Applications
- Spectator: A Powerful Tool to Simplify Your Angular Tests
- Transloco: The Internationalization library Angular
- error-tailer — Seamless form errors for Angular applications
- Forms Manager: The Foundation for Proper Form Management in Angular
- Cashew: A flexible and straightforward library that caches HTTP requests
- Error Tailor — Seamless form errors for Angular applications
And many more!
Follow me on Medium or Twitter to read more about Angular, Akita and JS!