I'm using a reactive form.when an input state is invalid i show an error.this is my view:
<div class="form-group">
<label for="username">Username</label>
<input name="username"
type="text"
class="form-control"
id="username"
formControlName="username"
#username/>
<div class="alert alert-danger"
*ngIf="formDir.form.controls.username.touched &&
formDir.form.controls.username.invalid">
This field is required.
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password"
id="password"
class="form-control"
name="password" />
</div>
<pre>{{myForm.value | json}}</pre>
<button class="btn btn-primary" type="submit">Sign in</button>
every time i want to use ngIf to show a validation error i have to write this unwieldy code:
*ngIf="formDir.form.controls.username.touched &&
formDir.form.controls.username.invalid">
it's more persecutor when you have more objects to validate.
by following documents on angular.io and this example i found a solution but i have to create an instance of every form control that i want to access it on view.
i'm looking for a solution like something we can use in template driven validation, using a temporary variable and ngModel like this:
<input type="text" class="form-control" name="username" #username="ngModel">
<div *ngIf="username.touched && username.invalid" class="alert alert-
danger">Email is required</div>
As i understand from this link there is no way to achieve this but this link is old and it may exists a solution in newer version of angular.
can you help me?
thanks