首页 > 解决方案 > 提交时将对象从父组件传递到子组件

问题描述

我正在尝试从父组件中获取值并将其传递给提交时的子组件,然后将其显示在子组件中。但是,该对象并未从 onSubmit 函数内部传递。因此,孩子不会显示任何新插入的值。

父 ts 文件:

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

父 html:

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

在儿童中:

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

子html:

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

标签: angulartypescript

解决方案


正如你对孩子的传递newStudent一样@Input(),检测它的变化并将新学生的变化传递给学生数组

父.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)
    }
  }

请注意,@Output()在子组件中定义将事件传递给父组件


推荐阅读