A view container is an Angular-managed location that holds and manages rendered views. A view is a region of HTML containing directives, bindings, and expressions. ViewContainerRef exposes the operations that create, remove, inspect, and position those views. section 15.2.1
The most useful ViewContainerRef operations include:
- createEmbeddedView(template) creates a view from a TemplateRef and inserts it into the container. section 15.2.1
- clear() removes all views from the container. section 15.2.1
- length reports the number of views, while get(index) and indexOf(view) support view lookup. section 15.2.1
- A single TemplateRef can be reused to create multiple views, each with different context data. section 15.3
Rendering one view per item
An iterating structural directive clears its container, loops through a data source, and calls createEmbeddedView for each object. It supplies a context containing $implicit, allowing the template variable in <ng-template let-item> to render item.name. section 15.3
Table 15.3. Useful ViewContainerRef methods and properties
|
Name
|
Description
|
|
element
|
This property returns an
ElementRef object that represents the container element.
|
|
createEmbeddedView(template)
|
This method uses a template to create a new view. See the text after the table for details. This method also accepts optional arguments for context data (as described in the “Creating Iterating Structural Directives” section) and an index position that specifies where the view should be inserted. The result is a
ViewRef object that can be used with the other methods in this table.
|
|
clear()
|
This method removes all the views from the container.
|
|
length
|
This property returns the number of views in the container.
|
|
get(index)
|
This method returns the
ViewRef object representing the view at the specified index.
|
|
indexOf(view)
|
This method returns the index of the specified
ViewRef object.
|
|
insert(view, index)
|
This method inserts a view at the specified index.
|
|
remove(Index)
|
This method removes and destroys the view at the specified index.
|
|
detach(index)
|
This method detaches the view from the specified index without destroying it so that it can be repositioned with the
insert method.
|
Browse the ViewContainerRef API table for view creation, removal, counting, lookup, and container-element access. section 15.2.1
