angular - ¿Cómo arreglar "No se puede establecer la propiedad de indefinido"?
Estoy creando un temporizador de cuenta regresiva en Angular, pero estoy obteniendo un TypeError al intentar llamar a una variable de otro componente. No puedo averiguar exactamente qué está causando este problema. Este es el video que estoy siguiendo: Temporizador de cuenta regresiva. A continuación está mi código:
Temporizador.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)
Este es mi código. Por favor, ayúdame.
Respuesta #1
Necesitas esperar a la inicialización del hijo con el hook AfterViewInit.
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
export class QuestionComponent implements OnInit, AfterViewInit {
ngAfterViewInit() {
this.counter.startAt = 2700;
this.counter.start();
}
}
