Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a input value to a parent component

I want to pass value of a input to a parent component. Currently I'm sending the whole input's ElementReffrom my child component. Is there an elegant way to doing this? I mean, I need to send only one number, not a whole reference.

Child Component:

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

@Component({
  selector: 'app-action-dialog-content',
  template: `
  <md-input-container>
      <input #amount md-input placeholder="Amount">
      <span md-suffix>€</span>
  </md-input-container>
  `
})
export class ActionDialogContentComponent {

  @ViewChild('amount') amount;

}

Parent Component:

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

import { ActionDialogContentComponent } from './../action-dialog-content/action-dialog-content.component';

@Component({
  selector: 'app-action-dialog',
  template: `
  <app-action-dialog-content></app-action-dialog-content>
  <md-dialog-actions>
      <button md-raised-button (click)="sendData()">ADD</button>
  </md-dialog-actions>
  `
})
export class ActionDialogComponent {

  @ViewChild(ActionDialogContentComponent) amountInput: ActionDialogContentComponent;

  sendData() {
    console.log(this.amountInput.amount.nativeElement.value);

  }

}
like image 513
Runtime Terror Avatar asked Oct 17 '22 19:10

Runtime Terror


1 Answers

You can use EventEmitter and Output from angular/core to emit data from the child component to the parent, which the parent component can then handle through event binding. See child to parent component interaction in the Angular 2 guides.

From your example:

Child:

export class ActionDialogContentComponent {

  amount: number;
  @Output() amountChanged: new EventEmitter<number>();

  changeAmount() { //Trigger this call from the child component's template
    this.amountChanged.emit(this.amount);
  }
}

Parent (note that the html event you are binding to matches the @Output property from the child component):

@Component({
  selector: 'app-action-dialog',
  template: `
    <app-action-dialog-component (amountChanged)="onAmountChanged($event)"></app-action-dialog-component>
    <md-dialog-actions>
      <button md-raised-button (click)="sendData()">ADD</button>
    </md-dialog-actions>
  `
})
export class ActionDialogComponent {

  onAmountChanged(amount: number) { 
    // do what you want with new value
  }
}
like image 135
ironmanwaring Avatar answered Oct 20 '22 18:10

ironmanwaring