Bellash
Bellash

Reputation: 8184

Two way binding between components in angular 2-4

I would like the child component value to be bound to the parent component. How to accomplish this when @Input() and [(ngModel)] are not enough ?

here is a plunker

Upvotes: 9

Views: 12410

Answers (3)

komron
komron

Reputation: 2277

You can make two-way data binding like following:

@Component({

selector: 'app-sizer',
  template: `
  <div>
    <button (click)="dec()" title="smaller">-</button>
    <button (click)="inc()" title="bigger">+</button>
    <label [style.font-size.px]="size">FontSize: {{size}}px</label>
  </div>`
})
export class SizerComponent {
  @Input()  size: number | string;
  @Output() sizeChange = new EventEmitter<number>();

  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }
}

And in template of parent component make two-way binding to size like following:

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

It (two-way binding) is just a syntax sugar for property binding, so it is equivalent to:

<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>

[(prop)] syntax using is possible when the prop has Input property called prop and event (Output property) that has a name propChange.

Code is from angular docs for more information navigate to this address: https://angular.io/guide/template-syntax#two-way-binding---

Upvotes: 8

Vivek Doshi
Vivek Doshi

Reputation: 58523

Here you have to set @Output also and change the component like

export class CounterComponent {

  @Output('initoChange') emitter: EventEmitter<string> = new EventEmitter<string>();
  @Input('inito') set setInitoValue(value) {
      this.count = value;
  }
  count: number = 0;

  increment() {
    this.count++;
    this.emitter.emit(this.count);
  }

  decrement() {
    this.count--;
    this.emitter.emit(this.count);
  }

}

Here is the link to plunker , please have a look.

Upvotes: 11

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7242

use @Output() for example

@Output() event: EventEmitter<Type> = new EventEmitter();

send data via emit function

send(): void {
  this.event.emit(data);
}

read more about EventEmitter

Upvotes: 0

Related Questions