I'm creating an Angular2 application with a Node backend. I will have forms that submit data to said backend. I want validation on both the client and server side, and I'd like to avoid duplicating these validation rules.
The above is somewhat irrelevant to the actual question, except to say that this is the reason why I'm not using the conventional Angular2 validation methods.
This leaves me with the following HTML structure:
<div class="form-group" [class.has-error]="hasError(name)">
<label class="control-label" for="name"> Property Name
<input id="name" class="form-control" type="text" name="name" [(ngModel)]="property.name" #name="ngModel" />
<div class="alert alert-danger" *ngIf="hasError(name)">{{errors.name}}</div>
</div>
<div class="form-group" [class.has-error]="hasError(address1)">
<label class="control-label" for="address1"> Address
<input id="address1" class="form-control" type="text" name="address1" [(ngModel)]="property.address.address1" #address1="ngModel" />
<div class="alert alert-danger" *ngIf="hasError(address1)">{{errors['address.address1']}}</div>
</div>
I will have some large forms and would like to reduce the verbosity of the above. I am hoping to achieve something similar to the following:
<my-text-input label="Property Name" [(ngModel)]="property.name" name="name"></my-text-input>
<my-text-input label="Address" [(ngModel)]="property.address.address1" name="address1" key="address.address1"></my-text-input>
I'm stumbling trying to achieve this. Particular parts that give me trouble are:
- Setting up two-way binding on the
ngModel(changes that I make in the component do not reflect back to the parent). - Generating the template reference variable (
#nameand#address1attributes) based on an@Inputvariable to the component.- It just occurred to me that perhaps I don't need a separate template reference variable name for each instance of the component. Perhaps I can just use
#inputsince it's only referenced from within that component. Thoughts?
- It just occurred to me that perhaps I don't need a separate template reference variable name for each instance of the component. Perhaps I can just use
- I could pass
errorsor aconstraintsobject to each instance of the component for validation, but I'd like to reduce repetition.
I realize that this is a somewhat broad question, but I believe that a good answer will be widely useful and very valuable to many users, since this is a common scenario. I also realize that I have not actually shown what I've tried (only explained that I have, indeed, put forth effort to solve this on my own), but I'm purposely leaving out code samples of what I've tried because I believe there must be a clean solution to accomplish this, and I don't want the answer to be a small tweak to my ugly, unorthodox code.