javascriptangularparameter-passingangular-event-emitter

How to pass data from child component to parent component when button clicked on parent component


I need to pass input's value from child component to parent component when user click on a submit button that exists in parent component.

childComp template

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

childComp TS file

export class PasswordInputComponent{

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

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

Parent Component Template

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

Parent Component TS file

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

It would easy to dio it if the button exists inside the child component. but in this case the value should be passed when the button in the parent component is clicked!


Solution

  • For single ChildComponent: Use ViewChild

    For multiple ChildComponent use: ViewChildren

    Parent Component TS file

    Single Child Component:

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

    Multiple Child Component:

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