简体   繁体   中英

How can I transfer form data from child to parent component in Angular

I want to pass the complete form data from one component "Register" to the root component(app-component). But as I am trying to printing the form data in app.component, it is just printing "object" and when I am trying to access the variables, it is showing as not defined.

  1. register.component.html
<div class="form-div">
    <form #regForm="ngForm" (ngSubmit)="collect(regForm.value)">
        <table>
            <tr>
                <td>User Name:</td>
                <td>
                    <input type="text" name="uname" class="form-control" [(ngModel)]="data.uname"></td>
                    <td>{{data.uname}}</td>
            </tr>
            <tr>
                <td>Contact:</td>
                <td>
                    <input type="number" name="contact" class="form-control"  [(ngModel)]="data.contact">
                </td>
                <td>{{data.contact}}</td>
            </tr>
            <tr>
                <td>Gender:</td>
                <td>
                    <input type="radio" name="gender" [(ngModel)]="data.gender" value="Female">Female
                    <input type="radio" name="gender" [(ngModel)]="data.gender" value="Male">Male </td>
                    <td>{{data.gender}}</td>
            </tr>
            <tr>
                <td>Qualification: </td>
                <td>
                    <span *ngFor="let item of qualification">
                        <input type="checkbox"  [(ngModel)]="item.ischecked" (change)="changeSelection()" name=" " id={{item.id}}/>
                        {{item.label}}
                    </span>
                </td>
                <td>
                    <span *ngFor="let item of selected">
                        {{item}}
                    </span>
                </td>

            </tr>
            <tr>
                <td>
                    State:
                </td>
                <td>
                    <select name="state" class="form-control"  [(ngModel)]="data.state">
                        <option value="Uttar Pradesh">Uttar Pradesh</option>
                        <option value="Delhi">Delhi</option>
                        <option value="Andhra Pradesh">Andhra Pradesh</option>
                        <option value="Uttarakhand">Uttarakhand</option>
                        <option value="Rajasthan">Rajasthan</option>
                    </select>
                </td>
                <td>{{data.state}}</td>
            </tr>
            <tr>
                <td>Address:</td>
                <td>
                    <textarea style="resize: none" name="address" class="form-control"  [(ngModel)]="data.address"></textarea>
                </td>
                <td>{{data.address}}</td>
            </tr>
            <tr>
                <td>Email</td>
                <td><input type="email" name="email" class="form-control"  [(ngModel)]="data.email"/>
                </td>
                <td>{{data.email}}</td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="Password" name="pass" class="form-control"  [(ngModel)]="data.pass"></td>
                <td>{{data.pass}}</td>
            </tr>
            <tr>
                <td><button type="reset" class="btn btn-warning">RESET</button></td>
                <td><button type="submit" class="btn btn-success">SUBMIT</button></td>
            </tr>
        </table>
    </form>
</div>
  1. register.component.ts
import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
  **@Output() sendToRoot:EventEmitter<object>=new EventEmitter();**
  constructor() {}
  ngOnInit(): void {
     this.fetchSelectedItems();
  }

  qualification=[
  {
    label:'Diploma',
    ischecked:false,
    id:'q1'
  },
  {
    label:'Graduate',
    ischecked:false,
    id:'q2'
  },{
    label:'Masters',
    ischecked:false,
    id:'q3'
  }];
  //function for featching selected qualifications
  selected:string[]=[];
  fetchSelectedItems() {
    this.selected.length=0;
    this.qualification.forEach((value,index)=>{
      if(value.ischecked){
        this.selected.push(value.label);
      }
    })
  }
  changeSelection() {
     this.fetchSelectedItems();
  }
  data={uname:"",
  contact:"",
  gender:"",state:"",address:"",email:"",pass:"",qualification2:this.selected};
  //function to be called on form submit
  **collect(evt:object){
    this.sendToRoot.emit(this.qualification);
    alert("Name: "+this.data.uname+"\nContact: "+this.data.contact+"\nGender: "+this.data.gender+"\nqualification: "+this.data.qualification2
      +"\nState: "+this.data.state+"\nAddress: "+this.data.address+"\nEmail: "+this.data.email+"\nPassword: "+this.data.pass);
  }**

}

  1. app.component.html
<app-register (sendToRoot)="getChild($event)"></app-register>  
  1. app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ReactiveForms';
  sendToDisplay:object={};
  **getChild(data:object){
    this.sendToDisplay=data;
    console.log(data); 
    console.log("from app.component.ts1: \n"+this.sendToDisplay)
    console.log(data.uname)// Error: uname does not exist on object
  }**
}

Basically your code is 100% working with only 1 issue

the below line

this.sendToRoot.emit(this.qualification);

You are emitting an array of qualification and expecting object!

If you need to get data then emit date not qualification

this.sendToRoot.emit(this.data);

See this demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM