首页 > 解决方案 > 我正在使用动态表单从表单中检索值,但是当我控制台记录我从该表单中的值创建的对象时,我得到了未定义

问题描述

@ViewChild('studentForm', {static: false}) studentForm: NgForm
students: Student[];

updatedStudent ={
  Student_ID: 0,
  Student_Name: '',
  Student_Number: '',
  Student_Surname: ''
 }

onUpdateStudent(studentForm: NgForm){
this.editMode = false;
const updatedStudentValue = studentForm.value
console.log(updatedStudentValue)
const updatedStudent = new Student(
  this.updatedStudent.Student_ID,
  updatedStudentValue.updatedStudent.Student_Name,
  updatedStudentValue.updatedStudent.Student_Number,
  updatedStudentValue.updatedStudent.Student_Surname
)
console.log(this.updatedStudent)

}

当我控制台记录 updatedStudentValues 时,我得到了我的学生的一个对象,但是当我尝试为我的学生模型制作一个对象时,它显示未定义的 Student_Name 我该如何解决这个问题。

任何帮助将非常感激!

export class Student {
 public Student_ID: number;
 public Student_Name: string;
 public Student_Number: number;
 public Student_Surname: string;

 constructor(
Student_ID: number,
Student_Name: string,
Student_Number: number,
Student_Surname: string
) {
this.Student_ID = Student_ID;
this.Student_Name = Student_Name;
this.Student_Number = Student_Number;
this.Student_Surname = Student_Surname;
}
}

我的错误

感谢您对我是 Angular 新手的任何帮助。

标签: angulartypescript

解决方案


this.updated student 与 const updatedStudent 不同。您应该创建如下对象:

this.updatedStudent = new Student(
  this.updatedStudent.Student_ID,
  updatedStudentValue.updatedStudent.Student_Name,
  updatedStudentValue.updatedStudent.Student_Number,
  updatedStudentValue.updatedStudent.Student_Surname
)
console.log(this.updatedStudent)

使用 const updatedStudent,您正在创建一个新对象,它是块范围的并且与 this.updatedStudent 没有关系


推荐阅读