如何修复“无法设置未定义的属性”?
Posted
技术标签:
【中文标题】如何修复“无法设置未定义的属性”?【英文标题】:How to fix "Cannot set property of undefined"? 【发布时间】:2020-07-19 21:28:49 【问题描述】:我正在用角度制作倒数计时器,但在尝试从另一个组件调用变量时收到 TypeError。我无法弄清楚究竟是什么导致了这个问题。这是我关注的视频:Countdown Timer 下面是我的代码:
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>
错误
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)
这是我的代码。请帮帮我。
【问题讨论】:
您没有在 QuestionComponent 中创建counter
的实例。添加一个构造函数。
看看这个Difference between Constructor and ngOnInit
@RamblinRose 你能告诉我如何创建,因为我是 Angular 的新手
不验证,请尝试将ngOnInit
钩子改为ngAfterViewInit
。
如果模板中没有 *ngIf,您也可以尝试将 static: true
属性添加到 @ViewChild
指令中
【参考方案1】:
您需要等待使用 AfterViewInit
钩子初始化子节点。
import Component, OnInit, ViewChild, AfterViewInit from '@angular/core';
export class QuestionComponent implements OnInit, AfterViewInit
ngAfterViewInit()
this.counter.startAt = 2700;
this.counter.start();
【讨论】:
以上是关于如何修复“无法设置未定义的属性”?的主要内容,如果未能解决你的问题,请参考以下文章
jQuery如何修复无法设置未定义的属性'_DT_CellIndex'?
如何解决 Bootstrap node.js 应用程序中的错误“无法设置未定义的属性 'emulateTransitionEnd'”?