angularangular2-directivesangularjs-bindings

Angular2 decorator for 2 way property binding


From Victor Savkin's post on Angular2 template syntax, shows how to use input and output property binding -

<todo-cmp [model]="todo" (complete)="onCompletingTodo(todo)"></todo-cmp>

@Component({selector: 'todo-cmp'})
class TodoCmp {
  @Input() model;
  @Output() complete = new EventEmitter(); // TypeScript supports initializing fields
}

The input property is decorated with @Input() while output property has @Output(). How should I declare a property which is going to have a 2 way property binding? Example: Assuming rootpanel component has 'suggestions' property (of type string) and searchPanel has 'getSuggestions property. Now I want the two properties to be bound to each other both ways. I tried -

rootpanel.html:

<search-panel [(getSuggestions)]="suggestions"> </search-panel>

But I am stuck while declaring the getSuggestions property in the searchPanel component. Also what should be the type of the getSuggestions property - string or EventEmitter<string>?

Please suggest.


Solution

  • If you want two-way model binding from the parent component:

    [(model)]
    

    You need the following in your child component:

    @Input() model: string;
    @Output() modelChange:EventEmitter<string>;
    

    At some point when the model is overwritten in your child component, you'll emit the modelChange event:

    updateModel(newValue:string) {
        this.model = newValue;
        this.modelChange.emit(this.model);
    }
    

    From the parent component's perspective, [(model)] is equivalent to:

    [model]="model"  (modelChange)="model=$event"
    

    In this way, when the model property changes inside a child component, the change in the model propagates upwards though two-way binding, synching all the bound models along the way.