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
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---
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With