Angular: 点击一次按钮,增加一个元素

发布时间 2023-07-24 11:11:54作者: 胸怀丶若谷

解决方案

思路

  1. 在组件的typesscript文件中,创建一个数组来存储每个按钮的信息
  2. 在模板中使用 *ngFor 指令来循环渲染按钮列表
  3. 在按钮事件的处理函数中,每次点击按钮时向按钮数组添加一个新的按钮信息

实例

在组件的typescript代码中

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

@Component({
  selector: 'app-project-demo',
  templateUrl: './project-demo.component.html',
  styleUrls: ['./project-demo.component.css']
})
export class ProjectDemoComponent implements OnInit {
  buttons: { label: string }[] = [];

  constructor() { }

  ngOnInit(): void {
  }


  addNewButton() {
    const newButtonLabel = `Button ${this.buttons.length + 1}`;
    this.buttons.push({ label: newButtonLabel });
  }

}

在html文件中

<button *ngFor="let button of buttons" [innerHTML]="button.label"></button>
<br>
<button (click)="addNewButton()">增加按钮</button>

效果图

image

代码截图

image