javascript - 当父组件上单击按钮时,如何将数据从子组件传递到父组件

标签 javascript angular parameter-passing angular-event-emitter

当用户单击父组件中存在的提交按钮时,我需要将输入的值从子组件传递到父组件。

childComp 模板

<input 
  type="password" 
  [(ngModel)]="userPasswordForm.inputId"
  class="mr-password-field k-textbox" 
  />

childComp TS 文件

export class PasswordInputComponent{

    constructor() { }
  
    @Output() inputValue = new EventEmitter<string>();
    userPasswordForm:any={'input':''};

  emitValue(value: string) {
    this.inputValue.emit(value);
  }
}

父组件模板

<child-component (inputValue)="" > </child-component>
<button (click)="getValueFromChild()"> </button>

父组件 TS 文件

tempUserFormPasswords:any=[];
.
.
.
getValueFromChild(receivedVal){
    this.tempUserFormPasswords.push(receivedVal);
}

如果按钮存在于子组件中,则很容易执行此操作。但在这种情况下,应该在单击父组件中的按钮时传递该值!

最佳答案

对于单个子组件: 使用ViewChild

对于多个 ChildComponent 使用:ViewChildren

父组件 TS 文件

单个子组件:

tempUserFormPasswords:any=[];
@ViewChild(ChildComponent) child: ChildComponent;
.
.
.
getValueFromChild(receivedVal){
    var data = child.getData();
    this.tempUserFormPasswords.push(data);
}

多个子组件:

tempUserFormPasswords:any=[];
@ViewChildren(ChildComponent) child: ChildComponent;
@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;
.
.
.
getValueFromChild(receivedVal){
    let data;
    children.forEach(child => (data = this.updateData(child.data));
    this.tempUserFormPasswords.push(data);
}

关于javascript - 当父组件上单击按钮时,如何将数据从子组件传递到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65923104/

相关文章:

javascript - JSON.stringify 在新创建的对象( Node 、javascript)上失败

javascript - 日期更改时的Jquery,更改另一个日期

angular2 ngbdatepicker 如何格式化输入字段中的日期

Angular 4 找不到名称 'ViewChild'

android - 将参数从 Activity 传递到服务中的线程

javascript - 使用 onclick 函数获取 rel 值

javascript - Tern 不会转到 Eclipse 中的定义

angular - 带有 angular-cli 的 SVG 图标系统

JavaScript 和编程初学者 - 传递函数解释

python - 函数参数 Python 的多个默认值