typescript 如何以Angular 创建阵列中的子构件

mutmk8jj  于 2023-02-25  发布在  TypeScript
关注(0)|答案(1)|浏览(140)

我有一个使用typescript的角记录器组件:

import { Component, EventEmitter, Output, Input } from '@angular/core';

interface Record {
  startTime: Date;
  endTime: Date;
  duration: number;
  isDone: boolean;
}

@Component({
  selector: 'app-record',
  templateUrl: './record.component.html',
  styleUrls: ['./record.component.css']
})
export class RecordComponent {
  @Input() buttonType: string;
  @Input() buttonName: string;
  @Output() valueEmitter = new EventEmitter<string>();

  constructor() {
    this.buttonType = 'start';
    this.buttonName = 'start';
  }

  private startTime: Date | null = null;
  private timer: any;
  public count = 0;
  public disabled = false;

  onClick(): void {
    if(!this.startTime) {
      this.startTimer();
    } else {
      this.stopTimer();
      this.buttonType='done';
      this.buttonName='done';
    }
  }

  startTimer(): void {
    this.buttonType='stop';
    this.buttonName='stop';
    this.startTime = new Date();
    this.timer = setInterval(() => {
      this.count ++;
    }, 1000);
  }

  stopTimer(): void {
    const endTime = new Date();
    const duration = endTime.getTime() - this.startTime!.getTime();
    clearInterval(this.timer);
    this.startTime = null;
    this.count = Math.floor(duration/1000);
    this.disabled = true;
    const value = 'TIMER_STOPPED';
    this.valueEmitter.emit(value);
  }
}

这是我的记录组件,当stopTimer触发时,我想在它下面再添加一个子组件。为此,我尝试发送一个值='TIMER_STOPPED';到父组件。下面是我的父组件:

import { Component } from '@angular/core';
import { RecordComponent } from '../record/record.component';

@Component({
  selector: 'app-tracker',
  templateUrl: './tracker.component.html',
  styleUrls: ['./tracker.component.css'],
})
export class TrackerComponent {
  public records:[] = [];

  addRecord(): void {
    const _record = new RecordComponent();
    _record.id++;
    _record.length = 1200;
    this.records.push(_record);
  }

  handleValue(value: string) {
    if (value === 'TIMER_STOPPED') {
      this.addRecord();
    }
  }
}

基本上,如果value === 'TIMER_STOPPED'意味着计时器停止,我想在数组顶部添加另一个组件(因此旧组件应该始终位于顶部),但我在Angular 方面确实是个新手。即使计时器停止,也无法添加新组件。这是解决此类问题的好方法吗?
谢谢你帮忙。
我实现了将值发送到父组件,但是在父组件中,我无法添加另一个子组件

0pizxfdo

0pizxfdo1#

不要向数组中添加组件。请改用数据。

  • 示例 *
class Record {
  public name: string;
  public length: number;
}

然后,您可以在父级中使用*ngFor循环它。

HTML父项

<div *ngIf="!records || records.length === 0">NO RECORDS</div>

<record-component *ngFor="let record of records" [buttonName]="record.name" [length]="record.length"></record-component>

要在父对象中添加新对象,请使用以下命令:

addRecord() {
  const _record = new Record();
  _record.name = "Test";
  _record.length = 1200;
  this.records.push(_record);
  
  // Wanna add it on top?
  // this.records.splice(0, 0, _record);
}

Here是一个堆栈 lightning 战示例。
所有其他将角为您做。

相关问题