响应式表单数组对象已更新但虚拟滚动列表未在前端更新

Reactive Form Array Object updated but Virtual Scroll list not updating on Front End

复制: https://stackblitz.com/edit/angular-rf-virtual-scroll

预期行为: 数据应附加在 UI

中的虚拟滚动列表中

实际行为

=> 虚拟滚动列表未更新(前端) => 响应式数组对象完美更新(在 ts 中)

这是因为 angular 只有在对象的引用发生更改时才会触发更改检测。但是通过添加新元素,items.controls 数组的引用保持不变。

您可以在添加新的 controls array 后创建副本,例如:

addOneNew(item = [true, 9999999]){
  const obj = this.createItem(item)
  this.items.push(obj);
  this.items.controls = [...this.items.controls]
  console.log(this.items.value)
}

通过分配新数组,更改检测将看到您的更改并更新您的视图。

希望这对您有所帮助...

app.component.html

    <div class="container">
    <div class="content" [formGroup]="testForm">
        <ng-container formArrayName="data" *ngFor="let item of testForm.get('data')['controls']; let i = index">
            <div [formGroupName]="i">
                Name: <input class="form-control" style="margin-bottom: 5px;" type="text" formControlName="name">
            </div>
        </ng-container>
    </div>
    <div class="row">
        <button class="btn btn-primary" (click)="addItem()">Add Name</button>
    </div>
</div>

app.component.ts

export class AppComponent implements OnInit {
 testForm: FormGroup;
 currentIndex = 0;
 constructor(
  private formBuilder: FormBuilder
 ) {}

 ngOnInit() {    
  this.testForm = this.createTestForm();
  this.initializeArray();
 console.log(this.testForm);

}

createTestForm(): FormGroup {
 return this.formBuilder.group({
   data: this.formBuilder.array([])
 });
}

get data(): FormArray {
 return this.testForm.get('data') as FormArray;
}

initializeArray() {
 for (let index = 0; index < 20; index++) {
   this.addItem();
 }
}

 addItem() {
   this.data.push(this.formBuilder.group({name: [`Name${this.data.length}`]}));
   this.currentIndex = this.data.length;
 }

 }