![](/img/trans.png)
[英]Object not passing from parent component to child onClick of submit button
[英]Passing object from parent component to child component on submit
我正在嘗試從父組件中獲取值並將其傳遞給提交時的子組件,然后將其顯示在子組件中。 但是,該對象不會從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>
正如您將newStudent
作為@Input()
傳遞給child,檢測其更改並將更改后的新學生傳遞給students數組
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)
}
}
請注意,子組件中定義了@Output()
以將事件傳遞給父組件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.