gpt4 book ai didi

Angular 6removeAt和trackBy更新formArray但不正确dom

转载 作者:行者123 更新时间:2023-12-02 03:24:26 27 4
gpt4 key购买 nike

我在 formGroup 中添加和删除 formArray。我使用 trackBy 跟踪要删除的 id。

好的索引传递给函数delete(i)并删除表单中好的formArray元素,但在dom中,最后一个每次都会消失。

我需要这个 trackBy,否则,当我在输入中写入时,我会失去焦点:-(。

my code simplified

删除时我试过了;过滤器,但我的对象是 FormArrayAbstractControl[]

最佳答案

formArrayName 必须在 *ngFor 之外,并且 *ngFor 位于 get('contacts').controls 之上

<div formArrayName="contacts" class="bloc-border bloc-color">
<div *ngFor="let item of siteForm.get('contacts').controls;
let i = index; " [formGroupName]="i">
<div class="col-sm-12" style="display:flex;">
<input class="form-control" type="text" [formControlName]="'type'">
- {{i}}
<button type="button" (click)="deleteContact(i)">DELETE</button>
</div>
</div>
</div>

更新有时使用直接 siteForm.get('contact').controls 会给我们一个错误(我认为在某些版本的 Anglar 中,但我不确定)。为了避免这种情况,我们可以创建一个 getter 来返回一个 formArray

get contacts():FormArray|null
{
return this.siteForm?this.siteForm.get('contacts') as FormArray:null
}

并使用

<div *ngFor="let item of contacts.controls;...> 

关于 Angular 6removeAt和trackBy更新formArray但不正确dom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53818620/

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