Skip to content

Commit a68b1a1

Browse files
renanmontebelokara
authored andcommittedMar 8, 2019
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
1 parent 014841d commit a68b1a1

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed
 

‎packages/forms/src/model.ts

+37
Original file line numberDiff line numberDiff line change
@@ -1895,6 +1895,43 @@ export class FormArray extends AbstractControl {
18951895
});
18961896
}
18971897

1898+
/**
1899+
* Remove all controls in the `FormArray`.
1900+
*
1901+
* @usageNotes
1902+
* ### Remove all elements from a FormArray
1903+
*
1904+
* ```ts
1905+
* const arr = new FormArray([
1906+
* new FormControl(),
1907+
* new FormControl()
1908+
* ]);
1909+
* console.log(arr.length); // 2
1910+
*
1911+
* arr.clear();
1912+
* console.log(arr.length); // 0
1913+
* ```
1914+
*
1915+
* It's a simpler and more efficient alternative to removing all elements one by one:
1916+
*
1917+
* ```ts
1918+
* const arr = new FormArray([
1919+
* new FormControl(),
1920+
* new FormControl()
1921+
* ]);
1922+
*
1923+
* while (arr.length) {
1924+
* arr.removeAt(0);
1925+
* }
1926+
* ```
1927+
*/
1928+
clear(): void {
1929+
if (this.controls.length < 1) return;
1930+
this._forEachChild((control: AbstractControl) => control._registerOnCollectionChange(() => {}));
1931+
this.controls.splice(0);
1932+
this.updateValueAndValidity();
1933+
}
1934+
18981935
/** @internal */
18991936
_syncPendingControls(): boolean {
19001937
let subtreeUpdated = this.controls.reduce((updated: boolean, child: AbstractControl) => {

‎packages/forms/test/form_array_spec.ts

+14
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,20 @@ import {of } from 'rxjs';
5959
expect(a.controls).toEqual([c1, c3]);
6060
});
6161

62+
it('should support clearing', () => {
63+
a.push(c1);
64+
a.push(c2);
65+
a.push(c3);
66+
67+
a.clear();
68+
69+
expect(a.controls).toEqual([]);
70+
71+
a.clear();
72+
73+
expect(a.controls).toEqual([]);
74+
});
75+
6276
it('should support inserting', () => {
6377
a.push(c1);
6478
a.push(c3);

‎tools/public_api_guard/forms/forms.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ export declare class FormArray extends AbstractControl {
170170
readonly length: number;
171171
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
172172
at(index: number): AbstractControl;
173+
clear(): void;
173174
getRawValue(): any[];
174175
insert(index: number, control: AbstractControl): void;
175176
patchValue(value: any[], options?: {

0 commit comments

Comments
 (0)
Please sign in to comment.