Angular “如何修复”;无法设置未定义的属性";?

Angular “如何修复”;无法设置未定义的属性";?,angular,typescript,rxjs,angular9,Angular,Typescript,Rxjs,Angular9,我正在用angular创建一个倒计时计时器,但在尝试从另一个组件调用变量时出现了TypeError。我无法确定到底是什么导致了这个问题。这是我下面的视频:下面是我的代码: Timer.component.ts import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; @Component({ selec

我正在用angular创建一个倒计时计时器,但在尝试从另一个组件调用变量时出现了TypeError。我无法确定到底是什么导致了这个问题。这是我下面的视频:下面是我的代码:

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 }`;
  }
}
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>

这是我的密码。请帮帮我。

您需要等待使用
AfterViewInit
钩子初始化孩子

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';

export class QuestionComponent implements OnInit, AfterViewInit {

    ngAfterViewInit() {
        this.counter.startAt = 2700;
        this.counter.start();
    }

}

您没有在QuestionComponent中创建
计数器的实例。添加一个构造函数。看到这个@RamblinRose你能告诉我如何创建吗?因为我在Angular方面是全新的,不需要验证它,请尝试将
ngOnInit
钩子更改为
ngAfterViewInit
。如果模板中没有*ngIf,你也可以尝试将
static:true
道具添加到
@ViewChild
指令中
import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';

export class QuestionComponent implements OnInit, AfterViewInit {

    ngAfterViewInit() {
        this.counter.startAt = 2700;
        this.counter.start();
    }

}