ViewContainerRef manages a collection of Angular views: regions of HTML containing directives, bindings, and expressions. Structural directives use it to create, insert, and remove template content. section 15.2.1
The most useful operations include:
- createEmbeddedView(template) creates a view from a TemplateRef and can receive context data and an insertion index. section 15.2.1
- clear() removes every view from the container. section 15.2.1
- length reports the number of views; get(index) retrieves a view; indexOf(view) finds its position; element returns the container ElementRef. section 15.2.1
Showing and hiding a template
Inject the container alongside the template, then react to the bound value: constructor(private container: ViewContainerRef, private template: TemplateRef<Object>) {}. Call this.container.createEmbeddedView(this.template) when the condition is true, and this.container.clear() when it becomes false. Angular supplies both constructor dependencies when it creates the directive. section 15.2.1
Creating repeated views
A structural iterator clears the container, loops through its data source, and creates one view per item: this.container.createEmbeddedView(this.template, new PaIteratorContext(this.dataSource[i])). The reusable TemplateRef supplies the markup, while the context object's $implicit property supplies each item to the template. 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 compact API table for ViewContainerRef properties and view-management methods. section 15.2.1
