javascript / expert
Snippet
Strict Template Type Guarding with ngTemplateContextGuard
To achieve full type safety in Angular templates for structural directives, you can use a static type guard. This tells the Angular Language Service the exact shape of the context object, enabling autocompletion and error checking inside the HTML.
snippet.js
1
2
3
4
5
6
7
8
9
interface UserContext<T> { $implicit: T; appRole: string; }@Directive({ selector: '[appUserCard]' })export class UserCardDirective<T> {static ngTemplateContextGuard<T>(dir: UserCardDirective<T>,ctx: any): ctx is UserContext<T> { return true; }}
angular
Breakdown
1
static ngTemplateContextGuard
A special static member recognized by the Angular compiler for template type-checking.
2
ctx is UserContext<T>
A TypeScript type predicate that narrows the 'any' context to a specific interface.