2

I have already looked at this similar question without success. The plunker mentioned in the question seems to be broken.

I am trying to update parent component's property from child component's [(ngModel)] binding.

This is the child components HTML:

<div class="elastic-textarea">
    <ion-input rows="1"  [value]="inputValue" [(ngModel)]="inputValue" (ngModelChange)="change($event)" ></ion-input>
    </div>

This is the child components TS:

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';

@Component({
  selector: 'app-childinput',
  templateUrl: './childinput.component.html',
  styleUrls: ['./childinput.component.css']
})
export class ChildinputComponent  {
@Input() inputValue: string;
  @Output() emitInputValue = new EventEmitter();
  constructor() { }

change(newValue) {
    console.log('newvalue', newValue)
    this.inputValue = newValue;
    this.emitInputValue.emit(newValue);
  }
}

This is how I'm using the child component in the parent component:

<app-childinput [(inputValue)]="thevalue" ></app-childinput>
<p>The changed value should be reflected here: {{thevalue}}</p>

Here is a STACKBLITZ demonstrating the issue. The parent component is the page callled "home", and the child component is the component called "childinput."

Am I doing something wrong or is this simply not possible anymore in Angular?

GeForce RTX 4090
  • 3,091
  • 11
  • 32
  • 58

2 Answers2

6

Just change emitInputValue to inputValueChange.

Fixed Stackblitz

Guerric P
  • 30,447
  • 6
  • 48
  • 86
  • 2
    I'll accept your answer as soon as I'm able to. But seriously?! The event emmiters name has got to be the same as @Input name, but with "Change" attached to its end? :D Why and is it documented anywhere at all? – GeForce RTX 4090 Aug 29 '18 at 16:04
  • @gfels yeah since the `Input` and `Output` are defined in the same scope, they chose this naming rule to be able to recognize an `EventEmitter` used for custom two-way databinding. You can find some documentation here: https://blog.angulartraining.com/tutorial-create-your-own-two-way-data-binding-in-angular-46487650ea82. Thank you in advance for the answer acceptance ;) – Guerric P Aug 29 '18 at 16:09
2

childinput.component.html

<div class="elastic-textarea">
    <ion-input rows="1"  [value]="inputValue" [ngModel]="inputValue" (ngModelChange)="change($event)" ></ion-input>
</div>

home.html and home.ts change

<app-childinput [(inputValue)]="thevalue" ></app-childinput>

to

<app-childinput [inputValue]="thevalue" (emitInputValue)="update($event)" ></app-childinput>


update(event) {
    this.thevalue = event;
  }

You declared Output EventEmitter emitInputValue, you didn't emit it properly. [(ngModel)] is two way binding which you mixed it with your Input decorator inputValue

enter image description here

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125