我有一個允許重復代碼的添加按鈕。
<div *ngFor="let detail of _detailRowNumber">
<mat-form-field appearance="fill">
<mat-label>Label of a detail</mat-label>
<input matInput type="text">
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Description of a detail</mat-label>
<input matInput>
</mat-form-field>
<button *ngIf="_detailRowNumber.length > 1" (click)="decreaseDetailRow(detail)" mat-fab color="primary" aria-label="Add a new row for a new detail">
<mat-icon>remove</mat-icon>
</button>
<button (click)="increaseDetailRow()" mat-fab color="primary" aria-label="Add a new row for a new detail">
<mat-icon>add</mat-icon>
</button>
</div>
_detailRowNumber: Array<number> = [0];
increaseDetailRow(): void {
this._detailRowNumber.push((this._detailRowNumber.length - 1) 1);
}
假設代碼將回圈 10 次。我的問題是,無論我點擊什么添加按鈕,它總是將代碼附加到最后一個位置。我想要的是在已單擊的按鈕部分之后附加代碼。我怎樣才能做到這一點?
我也用以下方法嘗試過,但我看不出有什么區別:
increaseDetailRow(index: number): void {
this._detailRowNumber.splice(index, 0, index );
}
uj5u.com熱心網友回復:
將代碼附加到最后一個位置是正常的,因為這就是push對陣列的作用。如果您想將它插入到特定位置,您可以嘗試使用splice陣列并從ngFor. 這應該有效,例如:
const arr = [1, 2, 3, 4];
arr.splice(1, 0, 3);
console.log(test); - [1, 3, 2, 3, 4]
這是關于 stackblitz 的一個簡單示例 - https://stackblitz.com/edit/angular-ivy-oycdbk?file=src/app/app.component.html。您可以看到當您單擊add按鈕時,如何在特定位置將具有值的元素index 1成功添加到該位置/索引,所以我認為您的splice邏輯也可能有效,但您看錯了,因為沒有當您使用模擬資料渲染相同的元素時,您可以看到很多差異。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/462669.html
標籤:javascript 有角度的 打字稿
