angular - 提交时将对象从父组件传递到子组件
问题描述
我正在尝试从父组件中获取值并将其传递给提交时的子组件,然后将其显示在子组件中。但是,该对象并未从 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()
,检测它的变化并将新学生的变化传递给学生数组
父.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()
在子组件中定义将事件传递给父组件
推荐阅读
- ms-access - 如何将 SQL 作为参数传递一个双精度值?
- java - 在 Python 中使用 Unicode 保持 Java 字符串偏移量一致
- reactjs - 使用动作更新 Redux 中嵌套对象的属性
- c# - 如何统一播放音频
- typescript - 带有索引的对象的打字稿定义模式
- go - 如何将不同类型作为 struct{} 传递给 GoLang 中的函数?
- sql-server - 如何获取特定日期的记录状态。SQL
- mips - 如何在 MIPS 中制作对口音不敏感的回文检查器?
- kdb - 如何从字符串列表创建多个字典?
- java-8 - 无法转换 java.util.Optional
带流