SlideShare a Scribd company logo
Generic Forms
Eliran Eliassy
About mySelf
• Experienced Front End
developer, specialized in
B2C applications.
• Front End Team Lead @
Market.co.uk
• Weekends FE developer @
fashbash.co
Where it all starts
Did you ever duplicate code of the same form?
Let’s wrap the input inside component?
Let’s wrap the input inside component?
Generic forms
Introducing ControlValueAccessor interface
Let’s build our
own custom
component!
•Requirements:
• Can show text fields
• Can fit for type text and
password
• Can Validate on required and
pattern
• Can show error messages
Live coding…
Create your custom-input component
Implement ControlValueAccessor
Generic forms
Let’s handle validations
Don’t forget to add the providers
How to our FormControl
• Injecting FormControlName, NgModel are options, but….you will tie
yourself to only one of them…
• NgControl is the super class of all the forms derctives: NgModel,
FormControlDirective and FormControlName.
• Why are we using the @Self decorator? Avoid providing the wrong
instance.
How to our FormControl
• Just don’t forget to remove the providers – NgControl will provide
them for you.
Validate considering base class validators
Show the errors on the template
Keep in mind
the async
state
And….That’s it!
• We can do it by implementing the controlValueAccessor again for our
wrap form
Now we want to re-use the whole form
• We can do it by implementing the controlValueAccessor again for our
wrap form
Now we want to re-use the whole form
But…There is maybe a quicker approche
• Start from add ControlContainer to your ViewProviders as
FormGroupDirective
• Why we using viewProviders and not the usual Providers?
FormGroupName directive
@Host() - Specifies that an injector should retrieve a dependency from any injector until
reaching the host element of the current component.
Now we want to re-use the whole form
• Then – inject the FormGroupDirective and set you local form to the
control container form
@Host() - Specifies that an injector should retrieve a dependency from any injector
until reaching the host element of the current component.
Now we want to re-use the whole form
Now you can setup you form and set validations
And…let’s actually use it
Our market-address-form will become a formControl inside our
addAddressForm formGroup!
And….That’s it!
Last second remarks
• Slides and git repo will be shared in the meetup comment
• Stay tuned – we starting a new monthly workshop @ Market
• Wanna join us?
• Keep in touch – eliran.eliassy@gmail.com
Generic forms

More Related Content

Generic forms