Providing Context Variables to Directives

Suppose we want to record some metadata on how our directive affected components and make this data available to them. For example, in our appDelay directive, we're making a setTimeout call, which in JavaScript's single-threaded asynchronous model means that it may not run after the exact time we provided. We'll capture the exact time it loads and make that variable available in the template.

  1. export class DelayContext {
  2. constructor(private loadTime: number) { }
  3. }
  4. @Directive({
  5. selector: '[appDelay]'
  6. })
  7. export class DelayDirective {
  8. constructor(
  9. private templateRef: TemplateRef<DelayContext>,
  10. private viewContainerRef: ViewContainerRef
  11. ) { }
  12. @Input()
  13. set appDelay(time: number): void {
  14. setTimeout(
  15. () => {
  16. this.viewContainerRef.createEmbeddedView(
  17. this.templateRef,
  18. new DelayContext(performance.now())
  19. );
  20. },
  21. time);
  22. }
  23. }

View Example

We've made a few changes to our appDelay directive. We've created a new DelayContext class that contains the context that we want to provide to our directive. In this case, we want to capture the actual time the createEmbeddedView call occurs and make that available as loadTime in our directive. We've also provided our new class as the generic argument to the TemplateRef function. This enables static analysis and lets us make sure our calls to createEmbeddedView pass in a variable of type DelayContext. In our createEmbeddedView call we pass in our variable which has captured the time of the method call.

In the component using appDelay, we access the loadTime context variable in the same way we access variables in ngFor.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <div *ngFor="let item of [1,2,3,4,5,6]">
  5. <card *delay="500 * item; let loaded = loadTime">
  6. <div class="main">{{item}}</div>
  7. <div class="sub">{{loaded | number:'1.4-4'}}</div>
  8. </card>
  9. </div>
  10. `
  11. })

View Example

原文: https://angular-2-training-book.rangle.io/handout/advanced-angular/directives/providing_context_variables_to_directives.html