feat(forms): clear (remove all) components from a FormArray (#28918)

This method is a more convenient and efficient way of removing all
components from a FormArray. Before it, we needed to loop the FormArray
removing each component until empty.

Resolves #18531

PR Close #28918
This commit is contained in:
Renan Montebelo
2019-02-21 22:47:07 -06:00
committed by Kara Erickson
parent 014841dfef
commit a68b1a1894
3 changed files with 52 additions and 0 deletions

View File

@ -1895,6 +1895,43 @@ export class FormArray extends AbstractControl {
});
}
/**
* Remove all controls in the `FormArray`.
*
* @usageNotes
* ### Remove all elements from a FormArray
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
* console.log(arr.length); // 2
*
* arr.clear();
* console.log(arr.length); // 0
* ```
*
* It's a simpler and more efficient alternative to removing all elements one by one:
*
* ```ts
* const arr = new FormArray([
* new FormControl(),
* new FormControl()
* ]);
*
* while (arr.length) {
* arr.removeAt(0);
* }
* ```
*/
clear(): void {
if (this.controls.length < 1) return;
this._forEachChild((control: AbstractControl) => control._registerOnCollectionChange(() => {}));
this.controls.splice(0);
this.updateValueAndValidity();
}
/** @internal */
_syncPendingControls(): boolean {
let subtreeUpdated = this.controls.reduce((updated: boolean, child: AbstractControl) => {