gpt4 book ai didi

Angular 9.0 - FormGroup 和 FormArray - 从表中删除行

转载 作者:行者123 更新时间:2023-12-04 01:13:47 24 4
gpt4 key购买 nike

我曾尝试使用单击按钮来删除行,但它不起作用,而且我不太确定我能做些什么来解决这个问题。

显示的初始 json 是:

{ "list": [ { "description": null, "status": false } ] }

当我点击移除按钮时,显示的json会变成:

{ "list": [] }

并且所选行根本没有被删除。

下面是代码。

todo-list.component.ts

todoListForm: FormGroup;

constructor(private toDoService: TodoService, private formBuilder: FormBuilder) {
this.createForm();
}

tableData: TableData[] = [
{ id: 'aaaaa', description: 'Go to market', status: true },
{ id: 'bbbbb', description: 'Buy groceries', status: true },
{ id: 'ccccc', description: 'Order pizza delivery', status: false },
];

ngOnInit(): void { }

createForm() {
this.todoListForm = this.formBuilder.group({
list: this.formBuilder.array([])
});

this.addList();
}

get list(): FormArray {
return this.todoListForm.get('list') as FormArray;
}

addList(): void {
const addTodoListForm = this.formBuilder.group({
description: [null, Validators.required],
status: [false]
});

this.list.push(addTodoListForm);

console.log('addTodoListForm', addTodoListForm);
console.log('list', this.list);
}

removeRow(i: number): void {
console.log(this.list);
this.list.removeAt(i);
}
}

export interface TableData {
id: string,
description: string,
status: boolean,
}

todo-list-component.html

<h1> To-do List </h1>
{{ todoListForm.value | json}}
<form [formGroup]="todoListForm">
<div formArrayName="list">
<div class="tableFlex">
<table class="table table-striped" table-layout="fixed">
<tr>
<th> #ID </th>
<th> Description </th>
<th> Action </th>
</tr>
<tr *ngFor="let data of tableData, let i = index">
<td> {{ i + 1 }} </td>
<td> <del *ngIf="data.status === true">{{data.description}}</del>
<div *ngIf="data.status === false">{{data.description}}</div>
</td>
<td>
<div class="btn-toolbar pull right">
<div class="btn-group mr-2" role="group" aria-label="Mark-as">
<button type="button" class="btn btn-secondary" (click)="updateStatus(i, data.status)">
{{ data.status === true ? 'Mark as incomplete' : 'Mark as completed' }} </button>
</div>

<div class="btn-group mr-2" role="group" aria-label="Remove">
<button type="submit" class="btn btn-danger" (click)="removeRow(i)">
Remove
</button>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</form>

最佳答案

通过添加变化检测器引用来尝试这一点

constructor(private readonly changeDetectorRef: ChangeDetectorRef){

}

removeRow(i: number): void {
this.list.removeAt(i);
this.changeDetectorRef.markForCheck();
}

如果这不起作用,也请尝试 this.detectChanges()。如果这也不起作用,您的更改将超出 ng 区域,那么您可以尝试以下操作

  removeRow(i: number): void {
this.zone.run(() => this.list.removeAt(i););
}

也将 Zone 注入(inject)到这个文件中

关于Angular 9.0 - FormGroup 和 FormArray - 从表中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64003106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com