What is an Angular View Container? | Concept

Ole Ersoy
Feb - 19  -  1 min

The ViewContainer provides an API that makes changes or dynamic updates to an View safe. It contains two types of Views:

  • Embedded: Views created from a TemplateRef instance.
  • Host: Views created using a component factory.

Any element can serve as a ViewContainer, but it’s usually implemented via <ng-container #viewcontainer></ng-container> as it is rendered as a comment and will not introduce additional DOM elements.

To get a reference to the ViewContainer within your AppComponent annotate the reference like this:

export class AppComponent implements AfterViewChecked {
       @ViewChild('viewcontainer', {read: ViewContainerRef}) viewContainer: ViewContainerRef;
}

You can also constructor inject a ViewContainerRef like this:

constructor(private vc: ViewContainerRef) {  }

In this case the ViewContainerRef will use the component host element as the insertion point for any embedded or host views.