Skip to content

Commit

Permalink
fix(core): trigger validation in ArrayType on field update (#3328)
Browse files Browse the repository at this point in the history
fix #3327
  • Loading branch information
aitboudad committed Jun 3, 2022
1 parent 6e9f7ac commit 90ef367
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/core/src/lib/extensions/field-form/field-form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ describe('FieldFormExtension', () => {
it('should add formControl for field with empty key', () => {
const field = createField({ defaultValue: 5 });

extension.prePopulate(field.parent);
extension.onPopulate(field);
expect(field.formControl).toBeDefined();
expect(field.formControl.value).toEqual(5);
Expand Down
10 changes: 9 additions & 1 deletion src/core/src/lib/extensions/field-form/field-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,15 @@ import { of } from 'rxjs';

/** @experimental */
export class FieldFormExtension implements FormlyExtension {
private root: FormlyFieldConfigCache;
constructor(private config: FormlyConfig) { }

prePopulate(field: FormlyFieldConfigCache) {
if (!this.root) {
this.root = field;
}
}

onPopulate(field: FormlyFieldConfigCache) {
if (!field.parent) {
return;
Expand All @@ -22,10 +29,11 @@ export class FieldFormExtension implements FormlyExtension {
}

postPopulate(field: FormlyFieldConfigCache) {
if (field.parent) {
if (this.root !== field) {
return;
}

this.root = null;
this.setValidators(field);
}

Expand Down
28 changes: 28 additions & 0 deletions src/core/src/lib/templates/field-array.type.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,34 @@ describe('Array Field Type', () => {
subscription.unsubscribe();
});

it('should validate field on add/remove', () => {
app.fields = [
{
key: 'foo',
type: 'array',
fieldArray: { fieldGroup: [{key: 'title', templateOptions: { required: true } }] },
defaultValue: [{ title: 'test' }],
},
];

const fixture = createFormlyTestComponent();
const form = app.form.get('foo') as FormArray;

expect(form.valid).toEqual(true);

// add
fixture.nativeElement.querySelector('#add').click();
fixture.detectChanges();

expect(form.valid).toEqual(false);

// remove
fixture.nativeElement.querySelector('#remove-1').click();
fixture.detectChanges();

expect(form.valid).toEqual(true);
});

it('should share formControl when field key is duplicated', () => {
app.fields = [
{
Expand Down

0 comments on commit 90ef367

Please sign in to comment.