Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind template reference variables to ngModel while using reactive forms

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

like image 593
Abolfazl Davoodi Shandiz Avatar asked Nov 07 '22 07:11

Abolfazl Davoodi Shandiz


1 Answers

Use an ngIf expression followed by a let, to rename the result of the expression:

<div *ngIf="formDir.form.get('username'); let c" class="form-group">
    <label for="username-id">Username</label>
    <input
       type="text"
       class="form-control"
       id="username-id"
       [formControl]="c" />
    <div class="alert alert-danger" *ngIf="c.touched && c.invalid">
        This field is required.
    </div>
</div>

You can also say:

<div *ngIf="formDir.form.controls.username; let c" ...>

If you don't happen to have a div or some other element you can use for the ngIf (the value of which is assumed to be always truthy), you can use an ng-container.

like image 120
Matthew Heaney Avatar answered Nov 14 '22 22:11

Matthew Heaney