Wrapping Angular FormField Component in Custom Angular Component
Environment
Product | Progress® Kendo UI® FormField for Angular |
Description
I am trying to wrap the FormField component in a custom component for reuse in an Angular Reactive Form.
This knowledge base article also answers the following questions:
- How to use the Kendo UI for Angular FormField component within custom components?
- How to correctly project content into a custom component wrapping a Kendo UI for Angular FormField?
- How to avoid the
only one control of type NgControl
error when using Kendo UI for Angular FormField in custom components?
Solution
To wrap the Kendo UI for Angular FormField component within custom components, follow the approach detailed below. This method involves wrapping the FormField component together with the desired form controls and conditionally rendering the desired form control based on specific situations.
-
Create a custom component that uses the
kendo-formfield
to wrap a Kendo UI for Angular DropDownList or MultiSelect component.html<!-- app.component.html --> <form class="k-form" [formGroup]="form"> <my-dropdown controlName="size" label="T-Shirt Size" [data]="sizes"></my-dropdown> <my-dropdown controlName="label" label="Color" [data]="colors"></my-dropdown> </form>
-
In your custom component, use the
kendo-formfield
to correctly bind the form control and pass necessary data.html<!-- my-dropdown.component.html --> <kendo-formfield showErrors="initial"> <kendo-label [for]="ddlLabel" [text]="label"></kendo-label> <kendo-multiselect #ddlLabel [formControlName]="formControl" [data]="data" > </kendo-multiselect> </kendo-formfield>
-
Ensure that the custom component correctly provides
ControlContainer
andFormGroupDirective
.tsimport { ControlContainer, FormGroupDirective } from '@angular/forms'; @Component({ selector: 'my-dropdown', viewProviders: [ { provide: ControlContainer, useExisting: FormGroupDirective }] })
The example below demonstrates the custom implementation in action.
Depending on your specific requirements, further modifications might be necessary. The key is to ensure that each form field within the custom component is correctly associated with a single form control instance.