Skip to content

Commit c353497

Browse files
Bjeaurncrisbeto
authored andcommitted
feat(forms): add support for pushing an array of controls to formarray (#57102)
Enables users to add an array of FormControls to a FormArray using its existing .push() method, instead of pushing each new FormControl one by one triggering events along the way. PR Close #57102
1 parent 01fec33 commit c353497

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

goldens/public-api/forms/index.api.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ export class FormArray<TControl extends AbstractControl<any> = any> extends Abst
259259
onlySelf?: boolean;
260260
emitEvent?: boolean;
261261
}): void;
262-
push(control: TControl, options?: {
262+
push(control: TControl | Array<TControl>, options?: {
263263
emitEvent?: boolean;
264264
}): void;
265265
removeAt(index: number, options?: {

packages/forms/src/model/form_array.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,16 @@ export class FormArray<TControl extends AbstractControl<any> = any> extends Abst
174174
* `valueChanges` observables emit events with the latest status and value when the control is
175175
* inserted. When false, no events are emitted.
176176
*/
177-
push(control: TControl, options: {emitEvent?: boolean} = {}): void {
178-
this.controls.push(control);
179-
this._registerControl(control);
177+
push(control: TControl | Array<TControl>, options: {emitEvent?: boolean} = {}): void {
178+
if (Array.isArray(control)) {
179+
control.forEach((ctrl) => {
180+
this.controls.push(ctrl);
181+
this._registerControl(ctrl);
182+
});
183+
} else {
184+
this.controls.push(control);
185+
this._registerControl(control);
186+
}
180187
this.updateValueAndValidity({emitEvent: options.emitEvent});
181188
this._onCollectionChange();
182189
}

packages/forms/test/form_array_spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ import {asyncValidator} from './util';
4141
expect(a.controls).toEqual([c1]);
4242
});
4343

44+
it('should support pushing an array', () => {
45+
a.push([c1, c2]);
46+
expect(a.length).toEqual(2);
47+
expect(a.controls).toEqual([c1, c2]);
48+
});
49+
4450
it('should support removing', () => {
4551
a.push(c1);
4652
a.push(c2);
@@ -971,6 +977,18 @@ import {asyncValidator} from './util';
971977

972978
a.push(c2);
973979
});
980+
981+
it('should fire an event once when calling `FormArray.push` with an array of controls', (done) => {
982+
a = new FormArray<any>([]);
983+
a.valueChanges.subscribe({
984+
next: (value: any) => {
985+
expect(value).toEqual(['old1', 'old2']);
986+
done();
987+
},
988+
});
989+
990+
a.push([c1, c2]);
991+
});
974992
});
975993

976994
describe('get', () => {

0 commit comments

Comments
 (0)