View Containers and Embedded Views

View Containers are containers where one or more Views can be attached. Views represent some sort of layout to be rendered and the context under which to render it. View containers are anchored to components and are responsible for generating its output so this means that changing which views are attached to the view container affect the final rendered output of the component.

Two types of views can be attached to a view container: Host Views which are linked to a Component, and Embedded Views which are linked to a template. Since structural directives interact with templates, we are interested in using Embedded Views in this case.

  1. import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
  2. @Directive({
  3. selector: '[appDelay]'
  4. })
  5. export class DelayDirective {
  6. constructor(
  7. private templateRef: TemplateRef<any>,
  8. private viewContainerRef: ViewContainerRef
  9. ) { }
  10. @Input()
  11. set appDelay(time: number): void {
  12. setTimeout(
  13. () => {
  14. this.viewContainerRef.createEmbeddedView(this.templateRef);
  15. },
  16. time);
  17. }
  18. }

View Example

Directives get access to the view container by injecting a ViewContainerRef. Embedded views are created and attached to a view container by calling the ViewContainerRef's createEmbeddedView method and passing in the template. We want to use the template our directive is attached to so we pass in the injected TemplateRef.

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