英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论