I am beginner in angular and I may need a little help with this thing. First of all I will just show how could it work then I will write about how I want it to work.
This is the regular way when you work with ngModel:
<form>
<input name="name" placeholder="name" [(ngModel)]="model.name" value="" />
<select name="select" [(ngModel)]="model.select">
<option value="1">..</option>
...
</select>
<input type="button" value=" click me" />
</form>
This is good enough if you don't want an own appearance for the select. My aim is to create a component for this where I can create divs and other contents that I can design to fit to the future display of this form element. On the other hand I want to keep the comfort of the ngModel. So the template should look like this in my aim:
<form>
<input name="name" placeholder="name" [(ngModel)]="model.name" value="" />
<app-select label="label" name="select" [placeholder]="'placeholder'" [(ngModel)]="select" [options]="options"></app-select >
<input type="button" value=" click me" />
</form>
I already tried to create something like this but I have failed, sadly :( Could some who has more experience then me help me with this please? Thanks your time and answers in advance!
I can recreate something minimal if necessary here: https://stackblitz.com/
Here is how I do this form my forms (keep in mind I am using reactive forms with the form builder, not template driven forms with ngModel):
First, I create a custom FormModule in a directory called
forms
.Next, inside there I have various form components. Let's use the
LoginFormComponent
for example.Here is the
LoginFormComponent
:Here is the HTML:
Now in any custom component that is within a module that imports
FormModule
, I can do the following:app.component.html:
app.component.ts:
The benefit of this sort of design may not be super obvious right away, but it enables us to do a few things:
login-form
component anywhere in our app as long as we import our customFormModule
. Any if we change it, it will be updated everywhere automatically. Keeps things DRY.login-form
component only contains the form itself, and any submission logic is handled outside of it for reuse-ability. This matters when you have forms that are used for both creation and editing. The button on edit can save data, where as the button on create can create something new. If you put the submit button inside the form component, this reuse isn't easily feasible.For slightly more complex forms, say a form that can take in some default values, take a look at this example
TagFormComponent
:This one follows the same general idea as the
LoginFormComponent
, except this one can pass in some default values for the form. Like this: