Royce  Reinger

Royce Reinger

1626345960

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 :

class Context<T> {
  $implicit!: T;
  subscribe!: T;

  constructor(value: T) {
    this.$implicit = value;
    this.subscribe = value;
  }
}

@Directive({ selector: '[subscribe]' })
export class SubscribeDirective<T> {
  @Input() set subscribe(source: Observable<T>) {
    // Subscribe and create the template
  }

  constructor(private tpl: TemplateRef<Context<T>>, 
              private vcr: ViewContainerRef) { }

}

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.

#angular2 #javascript #angular

Typing the Context Object in Angular Structural Directives