angular - 如何将输入值传递给父组件

标签 angular components

我想将输入的值传递给父组件。目前我正在从我的子组件发送整个输入的 ElementRef。有没有一种优雅的方法可以做到这一点?我的意思是,我只需要发送一个数字,而不是整个引用。

子组件:

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;

}

父组件:

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);

  }

}

最佳答案

您可以使用 angular/core 中的 EventEmitter 和 Output 将数据从子组件发射到父组件,然后父组件可以通过事件绑定(bind)处理这些数据。参见 child to parent component interaction在 Angular 2 指南中。

从你的例子:

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);
  }
}

父级(请注意,您绑定(bind)的 html 事件与子组件的 @Output 属性相匹配):

@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
  }
}

关于angular - 如何将输入值传递给父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641257/

相关文章:

angular - 如何创建自定义 Angular Material 模块?

angular - 如何处理我的 "expression has changed after it has been checked error"特殊情况

angular - http.get() 不返回可观察值

angular - 在 angular2 的自定义管道上扩展管道,如货币或数字

vue.js - 我们如何创建嵌套的 Vue 组件将其他元素作为其子元素传递

javascript - 从 react 中的另一个组件更新组件

image - Angular CLI - 如何在可重用组件中引用图像路径

javascript - Angular中的css封装

javascript - 如何从 Vue 组件中删除事件监听器

angularjs - 使用 ES6 测试 Angular 1.x 组件不会使用 $componentController 加载绑定(bind)