Skip to content

Commit

Permalink
fix(core): sync value changes for fields with same key (#1820)
Browse files Browse the repository at this point in the history
fix #1358
  • Loading branch information
aitboudad committed Oct 3, 2019
1 parent d60e0f5 commit 6f7a10a
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
22 changes: 22 additions & 0 deletions src/core/src/lib/components/formly.form.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,28 @@ describe('FormlyForm Component', () => {
expect(app.model.investments.length).toEqual(0);
});

it('should keep the value in sync when using multiple fields with same key', () => {
app = {
fields: [
{ key: 'name', type: 'text' },
{ key: 'name', type: 'text' },
],
form: new FormGroup({}),
options: {},
model: {},
};

const fixture = createTestComponent('<formly-form [form]="form" [fields]="fields" [model]="model" [options]="options"></formly-form>');

const inputs = fixture.debugElement.queryAll(By.css('input')) as DebugElement[];
inputs[0].nativeElement.value = 'First';
inputs[0].nativeElement.dispatchEvent(newEvent('input', false));

fixture.detectChanges();
expect(app.form.get('name').value).toEqual('First');
expect(inputs[1].nativeElement.value).toEqual('First');
});

it('should update the form controls when changing the model', () => {
app = {
fields: [{
Expand Down
10 changes: 8 additions & 2 deletions src/core/src/lib/components/formly.form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,17 @@ export class FormlyForm implements DoCheck, OnChanges, OnDestroy {
private trackModelChanges(fields: FormlyFieldConfig[], rootKey: string[] = []) {
fields.forEach(field => {
if (field.key && !field.fieldGroup) {
const control = field.formControl;
const valueChanges = field.modelOptions.debounce && field.modelOptions.debounce.default
? field.formControl.valueChanges.pipe(debounceTime(field.modelOptions.debounce.default))
: field.formControl.valueChanges;
? control.valueChanges.pipe(debounceTime(field.modelOptions.debounce.default))
: control.valueChanges;

this.modelChangeSubs.push(valueChanges.subscribe(value => {
// workaround for https://github.com/angular/angular/issues/13792
if ((control as any)._onChange.length > 0) {
control.setValue(value, {emitEvent: false});
}

if (field.parsers && field.parsers.length > 0) {
field.parsers.forEach(parserFn => value = parserFn(value));
}
Expand Down

0 comments on commit 6f7a10a

Please sign in to comment.