0

I've a simple component with a input for a string field:

import {Component, Input} from 'angular2/core';

@Component({
    selector: 'mundo-input',
    template: `
        <input class="form-control"  [(ngModel)]="zeit"  />
    `
})
export class MundoInputComponent  {
    @Input() zeit: string;    
}  

I am consuming this component like this:

<mundo-input [(zeit)]="myzeit"></mundo-input>

The myzeit-property from the outer component gets injected correctly. When I change the value by hand and press save on the outside component, the myzeit-property has the old value.

I changed the type of zeit from string to a Hero class (like in the NG2 Tutorial) and changed the binding of the input to zeit.name. The two-way databinding worked.

Is it possible to bind to a property of type string from the outer component? Or is it just possible with complex types (classes)?

Weissvonnix
  • 731
  • 7
  • 23

1 Answers1

0

You need to add an ouput to your component to be able to leverage two-way binding:

@Component({
  selector: 'mundo-input',
  template: `
    <input class="form-control" [ngModel]="zeit"
               (ngModelChange)="onChange($event)" />
  `
})
export class MundoInputComponent  {
  @Input() zeit: string;    
  @Output() zeitChange:EventEmitter<string> = new EventEmitter();

  onChange(val) {
    this.zeitChange.emit(val);
  }
}

By convention the output must have the zeitChange to be able to use the shortcut [(zeit)]="myzeit":

<mundo-input [(zeit)]="myzeit"></mundo-input>

In your case you only use one-way binding for the zeit parameter.

See this plunkr: https://plnkr.co/edit/snaM4y?p=preview.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360