I want to pass value of a input to a parent component. Currently I'm sending the whole input's ElementRef
from 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);
}
}
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
}
}
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