Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 757
Bellash Avatar asked Nov 02 '17 11:11

Bellash


2 Answers

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---

like image 176
komron Avatar answered Oct 24 '22 10:10

komron


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.

like image 44
Vivek Doshi Avatar answered Oct 24 '22 12:10

Vivek Doshi