Angular报错Property 'display' is used before its initialization解决
报错解决方案
报错根因
你在类属性result的初始化阶段直接引用this.display,而display仅声明了类型没有显式赋初始值,被TypeScript判定为未初始化,因此抛出语法错误。
同时业务逻辑上也存在问题:display是随计时动态更新的变量,提前在result初始化时绑定this.display只会拿到初始值,后续display更新时result.length不会同步变化,最终你存入列表的时长永远是初始的undefined,不符合需求。
修复步骤
- 给
display添加初始值,解决语法报错,同时符合初始展示逻辑:
// 把原来的 display: string | undefined; 替换为 display = '0:0:0';
- 调整
result的赋值逻辑,不要提前初始化,而是在保存记录时再创建Result实例,拿到当前最新的计时时长。你可以直接删除提前声明的result类属性,在需要存数据的时候再生成实例即可。
代码优化建议
1. 合并存储列表,避免数据错位
你现在分开维护list(活动名)和duration(时长)两个列表,很容易出现索引不匹配导致的渲染错位,直接用一个列表存储完整的计时记录即可。
2. 优化时间格式化逻辑,给分钟、秒补零
现有格式化逻辑会出现0:0:1这类显示不规范的问题,调整为自动补两位。
3. 合并按钮点击事件,避免执行顺序混乱
OK按钮绑定了3个click事件,执行顺序不可控,合并为一个方法处理所有保存逻辑。
4. 优化类型定义,避免使用any
给所有变量添加明确类型,提升代码可维护性,同时避免重复启动计时器的逻辑漏洞。
优化后完整代码
TS代码
import { Component, OnInit } from '@angular/core'; import { Activity } from '../activity'; import { Result } from '../result'; // 扩展记录类型,同时包含活动信息和计时结果 interface TimerRecord extends Result { name: string; } @Component({ selector: 'app-timer', templateUrl: './timer.component.html', styleUrls: ['./timer.component.css'], }) export class TimerComponent implements OnInit { time = 0; display = '0:0:0'; interval: number | undefined; modalboxActive = false; activity: Activity = { name: '', }; // 统一存储所有计时记录 recordList: TimerRecord[] = []; ngOnInit() {} addTask() { // 保存时生成最新的Result实例 const newRecord: TimerRecord = { name: this.activity.name, start: undefined, // 后续开发开始时间存储时补充 end: undefined, // 后续开发结束时间存储时补充 length: this.display }; this.recordList.push(newRecord); // 重置状态 this.activity.name = ''; this.modalboxActive = false; this.clearTimer(); } clearTimer() { clearInterval(this.interval); this.interval = undefined; this.time = 0; this.display = '0:0:0'; } startTimer() { // 避免重复启动计时器 if (this.interval) return; this.interval = window.setInterval(() => { this.time++; this.display = this.transform(this.time); }, 1000); } transform(value: number): string { const hours = Math.floor(value / 3600); const minutes = Math.floor((value - hours * 3600) / 60); const seconds = value - hours * 3600 - minutes * 60; // 给分钟、秒补零 return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; } pauseTimer() { clearInterval(this.interval); this.interval = undefined; } stopTimer() { this.modalboxActive = true; clearInterval(this.interval); this.interval = undefined; } }
HTML代码
<div class="modalbox" [class.active]="modalboxActive"> <div class="modal"> <p>What did you do?</p> <input type="text" [(ngModel)]="activity.name" #task /> <button (click)="addTask()" [disabled]="activity.name === ''" > OK </button> </div> </div> <div class="boxSuper"> <div class="boxLeft"> <div class="containerUp"> <button id="start" (click)="startTimer()">START</button> <button id="pause" (click)="pauseTimer()">PAUSE</button> <button id="stop" (click)="stopTimer()">STOP</button> </div> <div class="containerDown"> <p>{{ display }}</p> </div> </div> <div class="boxRight"> <div class="containerLeft"> <div class="leftList"> <ul class="listElement" *ngFor="let item of recordList"> <li> Length: <span>{{ item.length }}</span> </li> </ul> </div> </div> <div class="containerRight"> <div class="rightList"> <ul class="listElement" *ngFor="let item of recordList"> <li> Activity: <span>{{ item.name }}</span> </li> </ul> </div> </div> </div> </div>
内容的提问来源于stack exchange,提问作者tearex
相关产品推荐
相关产品推荐

