我目前正在使用 TypeScript 開發 Angular 前端。我正在嘗試從陣列元素中獲取復選框值,我正在使用 ngFor 在 HTML 檔案中對其進行迭代,并將這些值添加到總值中。總值應顯示在網頁上。
選中復選框后,我設法獲得了該值,并根據選中的復選框值增加了總值。但是,一旦取消選中復選框,就缺少減少總值的邏輯。那就是我需要幫助的地方。
不幸的是,我在取消選擇時找不到減法邏輯的具體實作。許多 SO 帖子包括我無法使用的 JQuery,因為盡管沒有錯誤,但 JQuery 代碼無法運行(我使用 npm 在 Angular 中安裝了 Jquery)。
HTML 檔案:
<span name="total" id="grandtotal">estimation total: {{grandtotal}}</span>
<ul *ngFor="let ticket of tickets">
<li>
<span>Estimation: {{ticket.estimation}}</span>
<b>ID: {{ticket.id}}</b>
<input
type="checkbox"
id="ticket.id"
(click)= "calculateTotal(ticket.estimation)">
<li/>
<ul/>
打字稿檔案:
totalValue: number = 0;
public calculateTotal(checkboxValue: number): void {
var checkboxes = <HTMLInputElement> document.getElementById('ticket.id');
if(checkboxes.checked) {
this.totalValue = this.totalValue checkboxValue;
}
}
uj5u.com熱心網友回復:
您可以使用一組工單來填充模板驅動的表單。
將選擇屬性添加到您的工單
type Ticket = {
id: number;
estimation: number;
select: boolean;
};
填充陣列:
tickets: Ticket[] = [
{ id: 1, estimation: 100, select: false },
{ id: 2, estimation: 150, select: false },
];
更改代碼以遍歷所有票證
public calculateTotal(): void {
let total = 0;
this.tickets.forEach((el) => {
if (el.select) {
total = el.estimation;
}
});
this.grandtotal = total;
console.log('Calc');
}
并稍微更改您的 HTML:
<span name="total" id="grandtotal">estimation total: {{ grandtotal }}</span>
<ul>
<li *ngFor="let ticket of tickets">
<span>Estimation: {{ ticket.estimation }}</span>
<b>ID: {{ ticket.id }}</b>
<b> selection:{{ ticket.select }}</b>
<input
type="checkbox"
id="ticket.id"
[(ngModel)]="ticket.select"
(change)="calculateTotal()"
/>
</li>
</ul>
請參閱 stackblitz 中的作業示例:https ://stackblitz.com/edit/angular-ivy-i7zmv2?file=src/app/app.component.ts
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489718.html
標籤:javascript html jQuery 有角度的 打字稿
