3
votes

I want to access the text I have in a text area in my child component to put it on the parent component and keep it updated.

I was told that @input in angular 4 is supposed to perform two-way binding. But I can't do that that way, and I don't understand why.

I found a workaround for this issue. It includes an @Output to send the info to the parent component. But if Input already does that (in some way I don't know), I want to avoid it.

For example, this is my Parent Component

import { Component } from '@angular/core';

@Component({
    selector: 'app-settings',
    templateUrl: './settings.component.html',
})
export class SettingsComponent {

    private studyDesignText =  'Text';

    constructor() {
    }

    public handleStudyDesignUpdated(designText: any) {
        this.studyDesignText = designText;
    }

}

It's html

<div class="section section-trials-settings-parent light rounded">
  <div class="section section-trials-settings-child">
    <div class="pure-g">
      <div class="pure-u-1-1">
        <app-settings-study-design
          [studyDesignText]="studyDesignText">
        </app-settings-study-design>
      </div>
    </div>
  </div>
</div>

My child component:

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

@Component({
  selector: 'app-settings-study-design',
  templateUrl: './settings-study-design.component.html',
})
export class SettingsStudyDesignComponent implements OnInit {

  @Input() studyDesignText: string;

  constructor() {
  }

  ngOnInit() {
    super.onInit();
    loadControls();
  }

  loadControls(): void {
    this.startAllTextAreas();
  }

  private startAllTextAreas() {
    this.startTextArea('study-design-textarea');
  }

  private startTextArea(htmlId: string) {
    // code to configure my text area; it's right...

}

If I change the value in the text area and send a signal with @Output so my parent component can be notified and console log the value, the printed value is the initial one. My friend did the same thing and it worked.

What am I missing?

1
you need an EvenEmitter<string> and use the same event handler in your parent - Niladri
The idea is to avoid using EventEmitter. Is there any other way? - GunterJameda

1 Answers

4
votes

@Input() is always one way binding from parent->child. Two way binding happens in this case, only when you have object as an input property. This is because, the reference for objects remain the same. And when one of the object updates, the other will also get updated. This is not true for string or number. It is always one way binding.