Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically populate a controls list or options based on a related controls value #1055

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Explore the [**live sample**](http://ng2-dynamic-forms.udos86.de/sample/index.ht
- [Form Control Configuration](#form-control-configuration)
- [Form Control Events](#form-control-events)
- [Updating Form Controls](#updating-form-controls)
- [Dynamic Option and List Population](#dynamic-form-control-option-and-list-population)
- [Custom Templates](#custom-templates)
- [Custom Validators](#custom-validators)
- [Custom Form Controls](#custom-form-controls)
Expand Down Expand Up @@ -689,6 +690,123 @@ To optimize this you can optionally pass a `DynamicFormComponent` to `detectChan
this.formService.detectChanges(this.formComponent);
```

## Dynamic Option And List Population
A common use case of more complex forms is having select, datalist, checkboxes and radio buttons automatically populate based on another form controls value. NG Dynamic Forms accomplishes this by allowing you to provide a `service`, per form control, which will get invoked when the related form controls value changes.

### Configuration
To connect a form control one will need to include the `dataProvider` attribute along with a `relation` and `service`. See the definitions below.

| Name | Description |
| :--- | :--- |
| relation | Similar to how relations work, you provide a rootPath or id to the related control |
| *relation*.id | ID of the input control |
| *relation*.rootPath | The path to the input control from the form group. |
| service | A token representing the service in the DI. |

```typescript
export function WikiPageForm(): DynamicFormControlModel[] {
return [
new DynamicInputModel({
id: 'wiki-title',
label: 'Search Title',
value: '',
validators: {
required: null,
},
errorMessages: {
required: '{{ label }} is required',
},
}),
new DynamicSelectModel({
id: 'wiki-page',
label: 'Wiki Page',
value: '-1',
options: [{value: '-1', label: '-- select a wikipedia page'}],
dataProvider: {
relation: {id: 'wiki-title'},
service: WikipediaService,
},
relations: [
{
match: MATCH_DISABLED,
when: [
{
rootPath: 'wiki-title', value: '',
},
],
},
],
validators: {
required: null,
},
errorMessages: {
required: '{{ label }} is required',
},
})
];
}
```
### Data Provider
NG Dynamic forms will look attempt to inject a given service via the token provided by the `dataProvider.service` definition. Your service must implement one of two methods depending on your form control.

| Control Name | Interface |
| :--- | :--- |
| DynamicInputModel | DynamicFormControlListDataProvider\<T> |
| DynamicSelectModel | DynamicFormControlOptionDataProvider\<T> |
| DynamicSelectModel | DynamicFormControlOptionDataProvider\<T> |
| DynamicRadioModel | DynamicFormControlOptionDataProvider\<T> |
| DynamicCheckboxModel | DynamicFormControlOptionDataProvider\<T> |

```typescript
const WIKI_URL = 'https://en.wikipedia.org/w/api.php';
const PARAMS = new HttpParams({
fromObject: {
action: 'opensearch',
format: 'json',
origin: '*',
},
});

@Injectable({
providedIn: 'root',
})
export class WikipediaService
implements DynamicFormControlListDataProvider<string>, DynamicFormControlOptionDataProvider<string> {
constructor(private http: HttpClient) {}

fetchList(value: string): Observable<string> {
return this.fetch(value);
}

fetchOptions(value: string): Observable<DynamicFormOptionConfig<string>[]> {
return this.fetch(value).pipe(map(
response => {
if (!Array.isArray(response)) {
return [];
}

return response.map((val) => {
return {
label: val,
value: val as string,
} as DynamicFormOptionConfig<string>;
});
}),
);
}

fetch(term: string): Observable<any> {
if (typeof(term) !== 'string' || term === '') {
return of([]);
}

return this.http
.get<any>(WIKI_URL, {params: PARAMS.set('search', term)}).pipe(
map(response => response[1]),
);
}
}
```

## Custom Templates

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import { isString } from "../utils/core.utils";
import { DynamicFormRelationService } from "../service/dynamic-form-relation.service";
import { DynamicFormGroupComponent } from "./dynamic-form-group.component";
import { DynamicFormArrayComponent } from "./dynamic-form-array.component";
import { DynamicFormDataService } from '../service/dynamic-form-data.service';

export abstract class DynamicFormControlContainerComponent implements OnChanges, OnDestroy {

Expand Down Expand Up @@ -77,7 +78,8 @@ export abstract class DynamicFormControlContainerComponent implements OnChanges,
protected layoutService: DynamicFormLayoutService,
protected validationService: DynamicFormValidationService,
protected componentService: DynamicFormComponentService,
protected relationService: DynamicFormRelationService) {
protected relationService: DynamicFormRelationService,
protected dataService: DynamicFormDataService) {
}

ngOnChanges(changes: SimpleChanges) {
Expand Down Expand Up @@ -287,6 +289,10 @@ export abstract class DynamicFormControlContainerComponent implements OnChanges,

this.subscriptions.push(...this.relationService.subscribeRelations(this.model, this.group, this.control));
}

if (this.model.dataProvider) {
this.subscriptions.push(this.dataService.connectDynamicFormControls(this.model, this.group));
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion projects/ng-dynamic-forms/core/src/lib/core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { DynamicFormLayoutService } from "./service/dynamic-form-layout.service"
import { DynamicFormValidationService } from "./service/dynamic-form-validation.service";
import { DynamicFormComponentService } from "./service/dynamic-form-component.service";
import { DynamicFormRelationService } from "./service/dynamic-form-relation.service";
import { DynamicFormDataService } from './service/dynamic-form-data.service';

@NgModule({
imports: [
Expand Down Expand Up @@ -35,7 +36,8 @@ export class DynamicFormsCoreModule {
DynamicFormLayoutService,
DynamicFormValidationService,
DynamicFormComponentService,
DynamicFormRelationService
DynamicFormRelationService,
DynamicFormDataService,
]
};
}
Expand Down
2 changes: 2 additions & 0 deletions projects/ng-dynamic-forms/core/src/lib/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export * from "./model/switch/dynamic-switch.model";
export * from "./model/textarea/dynamic-textarea.model";
export * from "./model/timepicker/dynamic-timepicker.model";

export * from "./model/misc/dynamic-form-control-data.model";
export * from "./model/misc/dynamic-form-control-layout.model";
export * from "./model/misc/dynamic-form-control-path.model";
export * from "./model/misc/dynamic-form-control-relation.model";
Expand All @@ -50,6 +51,7 @@ export * from "./service/dynamic-form-validators";

export * from "./service/dynamic-form.service";
export * from "./service/dynamic-form-component.service";
export * from "./service/dynamic-form-data.service";
export * from "./service/dynamic-form-layout.service";
export * from "./service/dynamic-form-relation.service";
export * from "./service/dynamic-form-validation.service";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { DynamicFormControlRelation } from "./misc/dynamic-form-control-relation
import { DynamicFormHook, DynamicValidatorsConfig } from "./misc/dynamic-form-control-validation.model";
import { serializable, serialize } from "../decorator/serializable.decorator";
import { isBoolean, isObject, isString } from "../utils/core.utils";
import {DynamicFormControlDataConfig} from './misc/dynamic-form-control-data.model';

export interface DynamicFormControlModelConfig {

Expand All @@ -20,6 +21,7 @@ export interface DynamicFormControlModelConfig {
relations?: DynamicFormControlRelation[];
updateOn?: DynamicFormHook;
validators?: DynamicValidatorsConfig;
dataProvider?: DynamicFormControlDataConfig;
}

export abstract class DynamicFormControlModel implements DynamicPathable {
Expand All @@ -38,6 +40,7 @@ export abstract class DynamicFormControlModel implements DynamicPathable {
@serializable() relations: DynamicFormControlRelation[];
@serializable() updateOn: DynamicFormHook | null;
@serializable() validators: DynamicValidatorsConfig | null;
@serializable() dataProvider: DynamicFormControlDataConfig | null;

private readonly disabled$: BehaviorSubject<boolean>;

Expand All @@ -63,6 +66,7 @@ export abstract class DynamicFormControlModel implements DynamicPathable {
this.disabled$ = new BehaviorSubject(isBoolean(config.disabled) ? config.disabled : false);
this.disabled$.subscribe(disabled => this._disabled = disabled);
this.disabledChanges = this.disabled$.asObservable();
this.dataProvider = config.dataProvider || null;
}

get disabled(): boolean {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {Observable} from 'rxjs';
import {DynamicFormOptionConfig} from '../dynamic-option-control.model';

export interface DynamicFormControlDataRelation {
rootPath?: string;
id?: string;
}

export interface DynamicFormControlDataConfig {
relation: DynamicFormControlDataRelation;
service: any;
}

export interface DynamicFormControlListDataProvider<T> {
fetchList(value: string): Observable<T[]>;
}

export interface DynamicFormControlOptionDataProvider<T> {
fetchOptions(value: string): Observable<DynamicFormOptionConfig<T>[]>;
}
Loading