再會。
我有一個陣列,我試圖在其中執行更新。我有一個基本的輸入欄位,用于向陣列添加新專案。我想要用于更新的相同輸入欄位。單擊編輯按鈕時,它會根據我單擊的專案填充該欄位,然后當我單擊更新時,將使用新專案更新陣列。
這是我到目前為止所擁有的。
應用程式組件.html
<div class="container">
<div class="jumbotron text-center">
<h1>Angular CRUD</h1>
</div>
<div class="container">
<form class="form-inline custom-centered" name="itemForm">
<label for="item">Add an Item:</label>
<input type="text" class="form-control" name="Value" id="Value" #item>
<button type="submit" class="btn btn-success" (click)="create(item.value); item.value=''" style="width: 80px;">Add</button>
</form>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of collection; let id = index">
<td>{{item.name}}</td>
<td>
<button (click)="editItem(id)" class="btn btn-info btn-sm mr-1">Edit</button>
<button (click)="deleteItem(id)" class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
</tbody>
</table>
app.component.ts
export class AppComponent {
collection: any = [];
create(item: any) {
this.collection.push({
name: item,
});
return;
}
editItem(){
}
deleteItem(id: any) {
this.collection.splice(id, 1);
}
}
有人可以就如何解決這個問題提供一些指導。
是否有任何內置方法可用于將“所選專案”系結到輸入欄位?
提前致謝。
uj5u.com熱心網友回復:
我建議使用反應式形式,它看起來像這樣:
export class AppComponent {
collection: any = [];
name = new FormControl('');
currentlySelectedId: number;
create() {
this.collection.push(this.name.value);
console.log(this.collection)
this.name.reset();
return this.collection;
}
editItem(id: any){
this.name.setValue(this.collection[id]);
this.currentlySelectedId = id;
}
update(){
this.collection.splice(this.currentlySelectedId, 1, this.name.value);
this.name.reset();
console.log("update collection", this.collection);
}
deleteItem(id: any) {
this.collection.splice(id, 1);
}
}
<div class="container">
<div class="jumbotron text-center">
<h1>Angular CRUD</h1>
</div>
<div class="container">
<form class="form-inline custom-centered" name="itemForm">
<label for="item">Add an Item:</label>
<input type="text" class="form-control" [formControl]="name" />
<button
type="submit"
class="btn btn-success"
(click)="create(name)"
style="width: 80px;"
>
Add
</button>
<button
type="submit"
class="btn btn-success"
(click)="update(name)"
style="width: 80px;"
>
Update
</button>
</form>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of collection; let id = index">
<td>{{ item }}</td>
<td>
<button (click)="editItem(id)" class="btn btn-info btn-sm mr-1">
Edit
</button>
<button (click)="deleteItem(id)" class="btn btn-danger btn-sm">
Delete
</button>
</td>
</tr>
</tbody>
</table>
注意[formControl]html 檔案中的 和name = new FormControl('');ts 檔案中的 。我還分離了用于創建和更新的 onclick 函式。就個人而言,我認為您應該允許就地編輯,這意味著一旦用戶單擊編輯顯示值的欄位,就可以進行編輯,而不是使用頂部輸入作為所有值的編輯欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/369139.html
下一篇:axios嘗試獲取串列時出錯
