I would like to move the form validation to directive and keep ngForm validation across all fields in the form. In the following example I move the input text field of the following validation (1. Works), to a directive. But when I move it to the directive, the model is updated correct, but the form.valid operation is not effected by the directive. The form is not valid, because input text has no value. When it is given a value the butten is activated and the form is valid.
1. Works:
<form (ngSubmit)="onSubmit()" #aliasForm="ngForm">
<div class="form-group">
<label for="firstname">Fornavn</label>
<input type="text" class="form-control" id="firstname"
required
[(ngModel)]="model.primaryAlias.firstName" name="firstname"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Fornavn er påkrævet
</div>
</div>
<div class="form-group col-sm-6">
<p-dropdown [style]="{'width':'150px'}" [options]="genders" [(ngModel)]="model.primaryAlias.gender" name="genders" [required]="true"></p-dropdown>
</div>
Opret
2. NOT working with directive (p-input):
<form (ngSubmit)="onSubmit()" #aliasForm="ngForm">
<p-input [(value)]="model.primaryAlias.firstName" directiveLabel="Fornavn"></p-input>
<div class="form-group">
<p-dropdown [style]="{'width':'150px'}" [options]="genders" [(ngModel)]="model.primaryAlias.gender" name="genders" [required]="true"></p-dropdown>
</div>
<button type="submit" class="btn btn-success pull-right" [disabled]="!aliasForm.form.valid">Opret</button></form>
p-input.html:
<div class="form-group">
<label for="firstname">Fornavn</label>
<input type="text" class="form-control" id="firstname"
required
[(ngModel)]="value" (ngModelChange)="onChange($event)" ngControl="value" name="firstname"
#name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Fornavn er påkrævet
</div>
How do I move the validation to a directive and keep the form handling, for the entire form intact ?
I would either implement
ControlValueAccessor
for your custom directive like:p-input.ts
parent.html
Stackblitz Example
or add inner input control to your form manually:
p-input.ts
parent.html
Stackblitz Example