lux
lux

Reputation: 8436

Two-way binding with @Input

I'm attempting to build a very simple component in Angular 2.0, a custom dropdown called <my-select>.

I am passing model into <my-select>, which I am expecting to be updated when the end-user chooses an option from the dropdown.

Plunker: http://plnkr.co/edit/iY1hG0q9rsgrR6ltKXW4?p=preview

As we can see from the Plunker, only the model object local to <my-select> is being updated, not the model object I passed in from <app>. What am I missing here? How does one two-way bind to a custom component?

In Angular 1.x, this was as simple as passing a variable into the $scope of the directive using =.

enter image description here

Upvotes: 2

Views: 677

Answers (2)

Mark Rajcok
Mark Rajcok

Reputation: 364677

If you use an object instead of a integer/primitive for the input property, the parent will see the changes, because both the parent and the child have the same object reference. (I suppose it is somewhat similar to Angular 1 = binding.) With this approach, you don't need to use events:

export class App {
    model = {value: 1};

export class MySelect {
  selectOption(event) {
    this.model.value = event;
  }

Plunker

I'm not sure if this is a recommended approach (i.e., events might be the only recommended approach to pass information to parents), but the heavy-loader example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs array property that is bound to the child components as input properties. The child components simply push() onto that array, and the parent component displays the array.

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657028

In your MySelect you need an output

@Output() modelChange:EventEmitter = new EventEmitter();

and then you notify parents about a changed value by modelChange.next(newValue);

See also Angular2: Passing values up from a component

Upvotes: 2

Related Questions