简体   繁体   中英

Passing object from parent component to child component on submit

I'm trying to fetch values from a parent component and pass it to the child component on submit, and then display it in the child component. However, the object is not getting passed from inside the onSubmit function. Hence the child does not show any newly inserted values.

Parent ts file:

@Output() StudentAdded= new EventEmitter<Stud>();

onSubmit(){
   const firstname=this.fname.value;
   const lastname=this.lname.value;
   const date=this.dob.value;
   const newStud = new Stud(firstname,lastname,date);
   this.StudentAdded.emit(newStud);
}

Parent html:

<div class="col-xs 5">
    <app-stud-details [student]="newStudent"  (StudentAdded)="studAdded($event)"></app-stud-details>
</div>

In child:

export class StudDetailsComponent implements OnInit { 
  @Input() student: Stud;
  students: Stud[]=[new Stud('Test','Test','05-11-1922')];

  constructor() { }

  ngOnInit() {
  }
  studAdded(student: Stud){
    this.students.push(student);
  }
}

Child html:

 <div class="col-xs-4" *ngFor="let student of students">
    {{'Name:'}}{{student.firstname}}{{' '+ student.lastname}}<br>
    {{'Date of Birth:'}}{{student.dob}}
  </div>

As you have are passing newStudent as @Input() to child, detect its change and pass the new student on change to the students array

Parent.ts

onSubmit(){
   const firstname=this.fname.value;
   const lastname=this.lname.value;
   const date=this.dob.value;
   const newStud = new Stud(firstname,lastname,date);
   this.newStudent = newStud 
}

Child.ts:

 ngOnChanges(changes: SimpleChanges) {
    const studChange = changes.student;

    if (studChange != undefined && studChange .previousValue != studChange .currentValue) {
      this.students.push(studChange.currentValue)
    }
  }

Please note that @Output() is defined in the child component to pass event to the parent

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