如何在运行时向页面添加元素

时间:2019-10-05 15:19:12

标签: angular typescript

我正在为大学创建一个有角度的演示Web应用程序,我想单击button将新节点添加到dom树。在JavaScript中,我将使用

document.getElementById('ticket-container').appendChild('app-ticket');

我似乎找不到答案,因此我认为这很简单。

在角度8中执行此操作的最佳方法是什么?

*ngFor="let ticket of ticketcount; index as i;

这是我的父组件ts文件:

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

class Ticket {
  name: string;
  price: number;

  constructor(x: string, y: number){
    this.name = x;
    this.price = y;
  }
}

@Component({
  selector: 'app-purchase-tickets',
  templateUrl: './purchase-tickets.component.html',
  styleUrls: ['./purchase-tickets.component.scss']
})

export class PurchaseTicketsComponent implements OnInit {
  total: number;
  ticketCount: number;

  constructor() {
   }

  ngOnInit() {
    this.total = 0;
    this.ticketCount = 0;
  }

  incrementTotal() {
    this.total += 5;
    this.ticketCount ++;
    this.renderNewTicket();
  }

  renderNewTicket() {
    //render ticket code here
  }
}

,模板文件为:

<main id='ticket-container'>
  <app-ticket ></app-ticket>
  <button mat-icon-button aria-label="new ticket" id="add-ticket" (click)="incrementTotal()" >
    <mat-icon>add</mat-icon> 
  </button>
</main>

<p>Total: €{{total}}</p>

2 个答案:

答案 0 :(得分:1)

正如我在评论中提到的,似乎您需要使用数组来存储项目,然后使用*ngFor

在UI上列出它们

在这里,尝试一下:

import { Component } from "@angular/core";

interface Ticket {
  name: string;
  price: number;
}

@Component({
  selector: "grid-list-overview-example",
  styleUrls: ["grid-list-overview-example.css"],
  templateUrl: "grid-list-overview-example.html"
})
export class GridListOverviewExample {
  tickets: Array<Ticket> = [];
  total: number;

  ngOnInit() {
    this.addTicket();
  }

  addTicket() {
    this.tickets.push({
      name: `Ticket ${this.tickets.length + 1}`,
      price: 10
    });
    this.calculateTotal();
  }

  calculateTotal() {
    this.total = this.tickets
      .map(ticket => ticket.price)
      .reduce((a, b) => a + b, 0);
  }
}

在您的模板中:

<main id='ticket-container'>
    <mat-grid-list cols="2" rowHeight="2:1">
        <mat-grid-tile *ngFor="let ticket of tickets">{{ ticket.name }}</mat-grid-tile>
    </mat-grid-list>

    <button mat-icon-button aria-label="new ticket" id="add-ticket" (click)="addTicket()" >
    <mat-icon>add</mat-icon> 
  </button>

  <p>Total: €{{total}}</p>
</main>

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:0)

您正在使用* ngfor,因此将与票证相关的值存储在一个数组(票证对象的数组)中,并在模板中使用它(与* ngfor一起使用)。 ticketCount是一个数字,* ngfor需要一个数组! 在TS文件中添加一个方法来处理按钮的click事件,然后在该数组中附加一个新值。用户界面会相应更新