1
votes

I am using the following.

1) FormBuilder

2) FormControl

I have created an error summary to show all the errors on form submit if the formControls input, radio, etc is not valid. What I would like to do is when the user clicks on the error message they should be taken to the input field that is invalid.

A few ways I know I can do it is:

  1. <a href="formControlElementID">Error message</a>

  2. Create a function to set focus on click

I know these can work but I am looking for an Angular specific solution if one exists. I am hoping for some sort of way to link using the form control name.

Ex:

<input
  formControlName="signupFirstName"
  matInput/>

<div id="error-summary>
  <a href="signupFirstName><p></p></a>

  or 

  <a angularDirective=""><p></p></a>
</div>

Is there anything built in with FormControl or Angular to link to a formControll input element? It seems redundant to use <a href="id"> as it would most likely be the same name as the formControl as well as it adds #id to the url which then adds more work for routing. The javascript way to set focus works but more code.

Based on these I am assuming there must be some sort of built in way to do this by now.

Update

Regarding @Vegas answer. This works well however, if you are using a formgroup you must call the template variable name different or else when passing the value to a child component as well as formControlName it will try and pass the template variable for both.

Incorrect:

<input #name formControlName="name">

<child-component [inputName]="name" [inputValidation]="name"

As well as trying to use [inputName]=name will cause same issue.

Correct:

<input #nameInputField formControlName="name">

<child-component [inputName]="nameInputField" [inputValidation]="name"
1

1 Answers

1
votes

One of the ways doing it, could be with template variables and ngIf:

<form novalidate (submit)="onLoginSubmit()" [formGroup]="user">
    Username <input id="username" type="text" #username autofocus formControlName="username">
    <br><br>
    Name <input id="name" type="text" #name autofocus formControlName="name">
    <ul>
        <li (click)="name.focus()" *ngIf="user.get('username').hasError('required')">Error on username</li>
        <li (click)="username.focus()" *ngIf="user.get('name').hasError('required')">Error on name</li>
    </ul>
</form>

Demo