Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/forms/src/model.ts
Expand Up @@ -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) => {
Expand Down
14 changes: 14 additions & 0 deletions packages/forms/test/form_array_spec.ts
Expand Up @@ -59,6 +59,20 @@ import {of } from 'rxjs';
expect(a.controls).toEqual([c1, c3]);
});

it('should support clearing', () => {
a.push(c1);
a.push(c2);
a.push(c3);

a.clear();

expect(a.controls).toEqual([]);

a.clear();

expect(a.controls).toEqual([]);
});

it('should support inserting', () => {
a.push(c1);
a.push(c3);
Expand Down
1 change: 1 addition & 0 deletions tools/public_api_guard/forms/forms.d.ts
Expand Up @@ -170,6 +170,7 @@ export declare class FormArray extends AbstractControl {
readonly length: number;
constructor(controls: AbstractControl[], validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null);
at(index: number): AbstractControl;
clear(): void;
getRawValue(): any[];
insert(index: number, control: AbstractControl): void;
patchValue(value: any[], options?: {
Expand Down