Reputation: 830
I have an Angular 2 (alpha 26) app in the works. I'm trying to arrange into sensible components and sub-components but having trouble with binding.
I have a Singleton model (let's call it AppModel) which I'm injecting successfully from my App component into the constructor of my first subcomponent (ItemBrowser).
From their I want a subcomponent (ItemEditor) to be able to see and reflect changes to AppModel.selectedItem. This can either be a subcomponent of App or ItemBrowser.
Currently it doesn't matter what I try, the changes to AppModel.selectedItem only show in ItemBrowser (where the change to AppModel.selectedItem is currently happening). It seems that model changes are not propagating down to subcomponents and I don't know how to force that refresh to take place.
I realize this is at the cutting edge, any help much appreciated.
I've tried passing the model as a Property but try as I might it just doesn't bind:
<item-browser [selectedItem]="AppModel.selectedItem"></item-browser>
Maybe I'm just missing an import. So far it's:
import {Component, bootstrap, View, NgFor, NgIf, DEFAULT, Injector, LifecycleEvent, onChange, EventEmitter } from "angular2/angular2";
[Update]
The solution was to Inject the shared model into the constructor of the child component, crucially including the @Parent() annotation:
export class ItemEditor{
appModel: AppModel;
constructor(@Parent() appModel: AppModel) {
this.appModel = appModel;
}
}
Upvotes: 3
Views: 3579
Reputation: 7254
There are three basic mechanisms for components to interact in Angular 2:
You can see the examples implemented here http://rawgit.com/SekibOmazic/angular2-playground/master/dist/index.html with the source code here https://github.com/SekibOmazic/angular2-playground
You would inject the children into the parent and call callbacks (you can also implement getter and setter function on the children). An example of this can be found here https://github.com/dylanb/Axponents/tree/master/angular2
In this example, the menuitems register themselves with their parent elements and then the parents call the children on certain events (for example to set the selected item, or when a sub-menu gets opened, to set the focus).
To implement this, you would implement a service that allows you to register listeners for changes on the model. Then you could call the callbacks for the listeners when data changes.
I consider this the least attractive of the three methods for Angular 2, because you have to get hold of the DOM element of the child in order to fire events on children. It is slightly better for communicating from a child to a parent because you can fire the event on your own DOM element and allow it to bubble up to the parent.
Upvotes: 2