Creating a Structural Directive

We'll create an appDelay structural directive that delays instantiation of a component or element. This can potentially be used for cosmetic effect or for manually handling timing of when components are loaded, either for performance or UX.

  1. @Directive({
  2. selector: '[appDelay]'
  3. })
  4. export class DelayDirective {
  5. constructor(
  6. private templateRef: TemplateRef<any>,
  7. private viewContainerRef: ViewContainerRef
  8. ) { }
  9. @Input()
  10. set appDelay(time: number): void { }
  11. }

View Example

We use the same @Directive class decorator as attribute directives and define a selector in the same way. One big difference here is that due to the nature of structural directives being bound to a template, we have access to TemplateRef, an object representing the template tag the directive is attached to. We also add an input property in a similar way, but this time with a set handler so we can execute some code when Angular performs the binding. We bind delay in exactly the same way as the Angular built-in structural directives.

  1. @Component({
  2. selector: 'app-root',
  3. template: `
  4. <div *ngFor="let item of [1,2,3,4,5,6]">
  5. <card *appDelay="500 * item">
  6. {{item}}
  7. </card>
  8. </div>
  9. `
  10. })
  11. export class AppComponent {
  12. }

View Example

Notice that no content is being rendered however. This is due to Angular simulating the html template tag and not rendering any child elements by default. To be able to get this content to render, we'll have to attach the template given by TemplateRef as an embedded view to a view container.

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