Skip to content

Commit

Permalink
feat(core): emit expressionChanges event through fieldChanges option (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
aitboudad committed Jul 12, 2020
1 parent eaa66ed commit 5d19b9f
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
1 change: 1 addition & 0 deletions src/core/src/lib/components/formly.field.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,5 +272,6 @@ export interface FormlyValueChangeEvent {
field: FormlyFieldConfig;
type: string;
value: any;
[meta: string]: any;
}

Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,48 @@ describe('FieldExpressionExtension', () => {
builder = formlyBuilder;
}));

describe('fieldChanges', () => {
it('should emit fieldChanges when expression value changes', () => {
const fields: FormlyFieldConfig[] = [
{
key: 'name',
expressionProperties: {
'templateOptions.label': 'field.formControl.value',
},
},
];
const spy = jasmine.createSpy('fieldChanges spy');
const subscription = options.fieldChanges.subscribe(spy);

builder.buildForm(form, fields, {}, options);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(
{
field: fields[0],
type: 'expressionChanges',
property: 'templateOptions.label',
value: null,
},
);

spy.calls.reset();
form.get('name').patchValue('foo');
options._checkField({ formControl: form, fieldGroup: fields, options });

expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(
{
field: fields[0],
type: 'expressionChanges',
property: 'templateOptions.label',
value: 'foo',
},
);

subscription.unsubscribe();
});
});

describe('field visibility (hideExpression)', () => {
it('should update field visibility', () => {
const fields: FormlyFieldConfig[] = [
Expand Down
17 changes: 16 additions & 1 deletion src/core/src/lib/extensions/field-expression/field-expression.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export class FieldExpressionExtension implements FormlyExtension {
}

if (field.options.fieldChanges) {
field.options.fieldChanges.next(<FormlyValueChangeEvent> { field: field, type: 'hidden', value: hide });
field.options.fieldChanges.next(<FormlyValueChangeEvent> { field, type: 'hidden', value: hide });
}
}

Expand Down Expand Up @@ -257,5 +257,20 @@ export class FieldExpressionExtension implements FormlyExtension {
control.patchValue(value, { emitEvent: false });
}
}

this.emitExpressionChanges(field, prop, value);
}

private emitExpressionChanges(field: FormlyFieldConfigCache, property: string, value: any) {
if (!field.options.fieldChanges) {
return;
}

field.options.fieldChanges.next({
field: field,
type: 'expressionChanges',
property,
value,
});
}
}

0 comments on commit 5d19b9f

Please sign in to comment.