【问题标题】:Passing object from parent component to child component on submit提交时将对象从父组件传递到子组件
【发布时间】:2019-06-25 09:38:33
【问题描述】:

我正在尝试从父组件获取值并在提交时将其传递给子组件,然后将其显示在子组件中。但是,该对象并未从 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>

【问题讨论】:

  • 输出装饰器上升,而不是下降。这意味着您要向那里的祖父母发送事件。
  • @Maryannah 哦,好的,那我该如何以另一种方式发送呢?
  • 在子进程中提供输出!
  • 还将studAdded方法移到父级
  • @Maryannah 如果我在孩子中提供输出,那么我会将数据从孩子发送给父母,对吧?

标签: angular typescript


【解决方案1】:

正如您将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()是在子组件中定义的,用于将事件传递给父组件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2016-12-16
    • 1970-01-01
    • 2018-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多