Angular 14 – 如何在向列表添加新项时动态渲染HTML/DOM

huangapple go评论79阅读模式
英文:

Angular 14 - How to dynamically render html/DOM when adding new item to a list

问题

以下是您要翻译的内容:

我有一个项目列表,我正在循环遍历并在一个 div 中显示。这些在初始页面加载时渲染。

<button (click)="addCut()" mat-raised-button color="primary">添加新的切割</button>
<button (click)="addCut()" mat-raised-button color="primary">+</button>
<div class="cutcontainer" style="margin-top:10px;" *ngFor="let i of details.cutsAndPrices; let index = index;">
  <mat-form-field class="cutitem">
    <input matInput placeholder="切割"> {{i.type}}
  </mat-form-field>
  <mat-form-field style="margin-right:15px;">
    <input matInput placeholder="价格"> {{i.price}}
  </mat-form-field>
  <button (click)="removeCut(index)" mat-raised-button color="warn" id="{{i.type}}">-</button>
</div>

我想要的是,当我点击第一个按钮时,它会调用 addCut(),向列表中添加一个项目,然后更新页面上的 HTML。

或者,如果更容易,只需在点击 addCut() 后在包含的 div 中添加以下内容:

<mat-form-field class="cutitem">
  <input matInput placeholder="切割">
</mat-form-field>
<mat-form-field style="margin-right:15px;">
  <input matInput placeholder="价格">
</mat-form-field>
<button (click)="removeCut(index)" mat-raised-button color="warn" id="">-</button>

希望这能理解,提前感谢。

英文:

I have a list of items I am looping through and displaying in a div. These render on initial page load.

<button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button>
<button (click)="addCut()" mat-raised-button color="primary">+</button>
<div class="cutcontainer" style="margin-top:10px;" *ngFor="let i of details.cutsAndPrices; let index = index;">
  <mat-form-field class="cutitem">
    <input matInput placeholder="Cut"> {{i.type}}
  </mat-form-field>
  <mat-form-field style="margin-right:15px;">
    <input matInput placeholder="Price"> {{i.price}}
  </mat-form-field>
  <button (click)="removeCut(index)" mat-raised-button color="warn" id="{{i.type}}">-</button>
</div>

I'm looking for a way of when I click the first button, it invokes addCut(), adds an item to the list and this then updates the html on the page.

Alternatively, if easier, just add

<mat-form-field class="cutitem">
  <input matInput placeholder="Cut">
</mat-form-field>
<mat-form-field style="margin-right:15px;">
  <input matInput placeholder="Price">
</mat-form-field>
<button (click)="removeCut(index)" mat-raised-button color="warn" id="">-</button>

inside of the containing div when I click addCut().

Hope this makes sense, Thanks in advance

答案1

得分: 2

在你的 .ts 文件中:

addCut(): void {
  this.details.cutsAndPrices.push(price); // price 是你想要的新元素
}
英文:

In your .ts file:

addCut(): void {
  this.details.cutsAndPrices.push(price); // price is your new element you want
}

huangapple
  • 本文由 发表于 2023年6月26日 23:41:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76558230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定