0 day streak
javascript / expert
Snippet

Advanced Structural Directives with Static Template Guarding

Structural directives can use a static method named 'ngTemplateContextGuard' to provide the Angular compiler with type information about the template context. This enables strict type checking inside the template (e.g., within an *appAuth block) for the '$implicit' property and other context members.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
interface UserContext<T> { $implicit: T; appAuth: string; }
@Directive({ selector: '[appAuth]' })
export class AuthDirective<T> {
// Static guard for template type checking
static ngTemplateContextGuard<T>(
dir: AuthDirective<T>,
ctx: any
): ctx is UserContext<T> { return true; }
constructor(private tr: TemplateRef<UserContext<T>>) {}
}
angular
Breakdown
1
static ngTemplateContextGuard<T>(...): ctx is UserContext<T>
A TypeScript type predicate that tells the compiler the shape of the context object used in the template.
2
constructor(private tr: TemplateRef<UserContext<T>>)
Injects the template with a specific context type, ensuring internal consistency.