I am currently working on an angular countdown timer and encountering a TypeError when attempting to access a variable from another component. I am struggling to identify the root cause of this issue. Here is the video tutorial that I am using as a reference: Countdown Timer. Below you can find my code:
Timer.component.ts
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-timer',
template: `<span>{{ currentValue }}</span>`,
styleUrls: ['./timer.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerComponent implements OnInit {
@Input() startAt = 0;
@Output() counter = new EventEmitter<string>();
currentValue = '';
constructor(private changeDetector: ChangeDetectorRef) { }
ngOnInit(){
}
public start(){
this.currentValue = this.formatValue(this.startAt);
this.changeDetector .detectChanges();
}
private formatValue(v){
const minutes = Math.floor(v/60);
const formattedMinutes = (minutes > 9) ? minutes : ('0' + minutes);
const seconds = v%60;
const formattedSeconds = (seconds > 9) ? seconds : ('0' + seconds);
return `${ formattedMinutes } : ${ formattedSeconds }`;
}
}
questions.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { TimerComponent } from '../timer/timer.component';
export class QuestionComponent implements OnInit {
@ViewChild('counter', { read: TimerComponent })
private counter: TimerComponent;
ngOnInit() {
this.counter.startAt = 2700;
this.counter.start();
}
}
question.component.html
<app-timer #counter></app-timer>
ERROR
core.js:6185 ERROR TypeError: Cannot set property 'startAt' of undefined
at QuestionComponent.ngOnInit (question.component.ts:122)
at callHook (core.js:4686)
at callHooks (core.js:4650)
at executeInitAndCheckHooks (core.js:4591)
at refreshView (core.js:11814)
at refreshDynamicEmbeddedViews (core.js:13154)
at refreshView (core.js:11819)
at refreshComponent (core.js:13229)
at refreshChildComponents (core.js:11527)
at refreshView (core.js:11848)
I would greatly appreciate any assistance in troubleshooting this issue with my code.