Encountering a peculiar issue here. I am using @Input to send data from the parent component to the child component, and even though I can retrieve the correct value in ngOnInit, I still receive an error message stating that the value is undefined. The data is clearly defined in the parent component, as confirmed by printing the values in both the parent and child components. Despite this, the error persists (even when attempting to access the data).
Attached are screenshots depicting the error and the retrieved value from console.log:
https://i.sstatic.net/lqlR5.png https://i.sstatic.net/HQZNI.png
Snippet of relevant parent HTML:
<quiz-course [quiz]="currentUnitQuiz"></quiz-course>
Parent Component TypeScript:
export class CoursePlayComponent implements OnInit {
errorMessage: string;
course: ICourse;
courseId: number;
public currentUnitQuiz: IQuiz;
public showQuiz: boolean;
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router,
private userProgressService: UserProgressService) { }
ngOnInit() {
this.courseId = JSON.parse(localStorage.getItem("courseId"));
this.getCourse(this.courseId);
}
getCourse(id: number) {
this.courseService.getCourse(id).subscribe(
course => {
this.course = course;
if (this.route.snapshot.firstChild.data.type == 'quiz') {
this.getQuiz(this.currentUnitPos);
}
},
error => this.errorMessage = <any>error);
}
getQuiz(currentUnitPosition: number) {
this.showQuiz = true;
this.currentUnitQuiz = this.course.units.find(u => u.position ===
currentUnitPosition).quiz;
}
}
EDIT: Further code has been added for clarity. The same error occurs when attempting to access the length property, yet the value can still be printed and retrieved as expected.
Child Component TypeScript:
export class CourseQuizComponent implements OnInit {
@Input() quiz: IQuiz;
public currentQuestion: IQuestion;
public currentIndex: number;
public currentUnit: number;
public userAnswers: number[] = [];
public correctAnswers: number;
constructor(private courseService: CourseService,
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder) { }
ngOnInit() {
console.log("length in child: ", this.quiz.questions.length); // **NOT** undefined
this.restartQuiz();
}
restartQuiz() {
this.currentUnit = +this.route.snapshot.paramMap.get('unitId');
this.correctAnswers = 0;
for(let i = 0; i < this.quiz.questions.length; i++) {
this.userAnswers[i] = 0;
}
this.getCurrentQuestion(0);
}
}
Interfaces:
export interface IQuiz {
id: number;
name: number;
unit_id: number;
unit_position: number;
questions: IQuestion[];
}
export interface IQuestion {
id: number;
name: string;
quiz_id: number;
position: number;
question: string;
answer1: string;
answer2: string;
answer3: string;
answer4: string;
correct: number;
selected: number;
}