Nesting Components
In component-based frameworks like Angular, React we create a root component and build a tree. With ngBackbone we can do the same. Let's create a new child component foo.ts
:
Then we add its sibling bar.ts
As you can see from the code both of the components render themselves during initialization. In the root app.ts
we can use views
map to refer to the nesting components:
Here we specified the locations for the child components in the template by placing there elements ng-foo
and ng-bar
. These are the elements we have bound our nested components to.
Child Component and Construction Options
Well, what if we need to pass specific constructor arguments to a nesting component? Not a problem. We can specify a subordinated component as an array where the constructor goes in the first element and view options in the second:
Child components get constructed after the parent first rendering. Thus they can bind to the elements of the parent template. Besides construction ngBackbone also takes care about destruction. Whenever
remove()
method is called on the parent, this method is being invoked per each child recursively.
Accessing Sub-components
Within parent component child ones are available in views
map. You can access the instance of a sub-component as this.views.get( "name" )
. Thus we obtain the control over child component from the parent:
Communicating between Parent and Child
As we just examined the parent component has the links to child ones. But every child component also has a link to the parent (this.parent
). We can use it to implement bi-directional communication.
Let's write a child component that has a bound echo
model. The template renders echo.msg
. When the component initializes it changes echo.msg
of it's parent, assuming the parent has similar model:
child.ts
Now we create the parent component. During initialization it also changes the model of the child.
parent.ts
When we compile the code and run it a browser, we see that parent received and displayed the message from child and vice versa.
Maintaining bindings on parent view change
Let's say we have an imaginary task. We have to create a list where every item has own view. So as for items the example view may look like:
The parent (list) view has a bound collection named items
and a subview named also items
. As you remember we expect subview binding to ng-item
element.
Initially the collection has just a single element and on render we have <ng-list><ng-item>it's item</ng-item></ng-list>
With method list.views.getAll( "foo" )
we can access the array of bound ItemView instances. Here it consists of one element. However let's see what happens if we change the collection:
The method list.views.getAll( "foo" )
indicates that we have now 2 subview instances matching ng-item
element. We can access a particular instance like list.views.get( "foo", index )
Last updated