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

标签 angular formarray

我在 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/

相关文章:

java - 将登录页面添加到现有的 angular2 应用程序

html - 将 sideNav 添加到元素后,粘性工具栏不起作用

可重用子组件中的 Angular react 形式 : Problem with FormArrays: `formGroupName` must be used with a parent formGroup directive

angular - 使用 Angular FormArray 计算值

angular - 剑道 : Insert a FormGroup at a top into a FormArray

angular - 用于确定 FormArray 的控件属性是 [FormControl] 还是 [FormGroup] 的选择器?

angular - 以 Angular 从html模板设置 typescript 变量的值

angular - 带有 @Host 参数的单元测试 Angular 9 组件无法解析参数

javascript - Angular FormArray 对象属性之间的交叉验证

html - Polymer paper-dropdown-menu 在浏览器中无法正确呈现