What is the correct way to bind a child to a parent shared model?

I have an Angular 2 app (alpha 26). I am trying to organize sane components and subcomponents, but I am having binding issues.

I have a Singleton Model (let's call it AppModel) that I am successfully injecting from my app component into the constructor of my first subcomponent (ItemBrowser).

From them, I want the subcomponent (ItemEditor) to be able to see and reflect the changes in the AppModel.selectedItem. It can be either a subcomponent of the application or an ItemBrowser.

It currently doesn't matter what I'm trying, the changes to AppModel.selectedItem only show up in the ItemBrowser (where the AppModel.selectedItem is currently changing). It seems that the model changes are not propagated to the subcomponents and I have no idea how to get this update to take place.

I understand this is to the cutting edge, any help is greatly appreciated.

I've tried passing the model as a property, but I'm trying to make it simple to bind:

<item-browser [selectedItem]="AppModel.selectedItem"></item-browser>

      

Maybe I'm just missing the import. While this:

import {Component, bootstrap, View, NgFor, NgIf, DEFAULT, Injector, LifecycleEvent, onChange,  EventEmitter } from "angular2/angular2";

      

[Update]

The solution was to inject the generic model into the constructor of the child component, including the @Parent () annotation:

export class ItemEditor{

  appModel: AppModel;

  constructor(@Parent() appModel: AppModel) {
    this.appModel = appModel;
  }
}
      

Run code


+3


source to share


1 answer


There are three main mechanisms for the interaction of components in Angular 2:

  • Events
  • Services
  • Injections

You can see examples implemented here http://rawgit.com/SekibOmazic/angular2-playground/master/dist/index.html with source code here https://github.com/SekibOmazic/angular2-playground

Injection

You inject children into the parent and call callbacks (you can also implement getter and setter function for children). An example of this can be found here https://github.com/dylanb/Axponents/tree/master/angular2



In this example, the menu items are registered with their parent items, and then the parents call the children on certain events (for example, to set a selected item or when a submenu opens to set focus).

Service

To do this, you must implement a service that allows you to register listeners for changes to the model. Then you can call callbacks on the listeners when the data changes.

Events

I find this the least attractive of the three methods for Angular 2, because you need to master the DOM element for the child in order to fire the events for the children. It's a little better for child-to-parent communication because you can fire the event on your own DOM element and let it bubble up to the parent.

+2


source







All Articles