Bryant11
Bryant11

Reputation: 333

Integrating component with ngModel in Angular2

Lets say I have the following scenario:

@Component({
  selector: 'my-app',
  template: `
    <my-component
        [(value)] = "value"
        (change)="onChange($event)"
    ></my-component>
    <br /><br />
    <input [(ngModel)]="value" />
  `,
  directives: [MyComponent]
})

Now if I change the value of the input he Component correctly gets the new value and performs some logic. What do I need to do in order to update the input value from the component (two-way).

Thanks

Upvotes: 1

Views: 271

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202316

You need to have an @Output element defined with the name valueChange like this:

@Component({
  (...)
})
export class MyComponent {
  @Input()
  value:string;
  @Output()
  valueChange:EventEmitter<string>;

  constructor() {
    this.valueChange = new EventEmitter();
  }

  updateValue() {
    this.value = 'some other value';
    // Will update the value in the parent component
    this.valueChange.emit(this.value);
  }
}

When calling the emit method on the event emitter, the value property in the parent component will be updated because you leverage the syntax <sub [(value)]="value"></sub>.

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

Upvotes: 2

Related Questions