Skip to content

Commit ddd7212

Browse files
JeanMecheatscott
authored andcommitted
fix(forms): reset() call with null values on nested group (#48830)
Non typed forms allow to pass null to nested groups when calling `formGroup.reset()`, this commit prevent an undefined access. fixes #20509 PR Close #48830
1 parent 59ba2a6 commit ddd7212

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

packages/forms/src/model/form_group.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -485,8 +485,9 @@ export class FormGroup<TControl extends {[K in keyof TControl]: AbstractControl<
485485
value: ɵTypedOrUntyped<TControl, ɵFormGroupValue<TControl>, any> = {} as unknown as
486486
ɵFormGroupValue<TControl>,
487487
options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
488-
this._forEachChild((control, name) => {
489-
control.reset((value as any)[name], {onlySelf: true, emitEvent: options.emitEvent});
488+
this._forEachChild((control: AbstractControl, name) => {
489+
control.reset(
490+
value ? (value as any)[name] : null, {onlySelf: true, emitEvent: options.emitEvent});
490491
});
491492
this._updatePristine(options);
492493
this._updateTouched(options);

packages/forms/test/form_group_spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -694,6 +694,19 @@ describe('FormGroup', () => {
694694
expect(g.disabled).toBe(false);
695695
});
696696

697+
it('should be able to reset a nested control with null', () => {
698+
const g = new FormGroup({
699+
id: new FormControl(2),
700+
nested: new FormGroup<any>({
701+
id: new FormControl(3),
702+
}),
703+
});
704+
705+
g.reset({id: 1, nested: null});
706+
expect(g.get('nested')?.value).toEqual({id: null});
707+
expect(g.get('nested.id')?.value).toBe(null);
708+
});
709+
697710
describe('reset() events', () => {
698711
let form: FormGroup, c3: FormControl, logger: any[];
699712

0 commit comments

Comments
 (0)