1

I have a GUI with many dynamically generated inputs.

I can assign the inputs dynamically generated id's like so:

<ul>
  <li *ngFor="#item of items" >
    <mat-form-field>
      <input type=number attr.id={{item.name}}}
    </mat-form-field>
  </li>
</ul>

I wish to be able to set the focus on a particular input with a dynamic name. Is this possible?

Because the id's are dynamically generated we cannot use the @viewchild approach like so:

@ViewChild('usernameField') usernameField: ElementRef;

ngAfterViewInit() {
  this.usernameField.nativeElement.focus();
}

There is some mention of a focus method, and FocusOptions in the material documentation, but no examples:

https://material.angular.io/components/input/overview

2
  • if the ids are dynamically generated inside an element you could use ViewChildren and listen for the changes Commented Sep 3, 2019 at 20:15
  • 1
    Can you not just use standard DOM operations? document.getElementById(myDynamicId).focus()? Commented Sep 3, 2019 at 21:23

1 Answer 1

1

You can use template logic to apply a template reference variable based on a condition (e.g. the id is a certain value) which then allows using ViewChild.

If you don't already know the id of the element you want focused, and the id is dynamically - as opposed to randomly - generated, then it is most likely predictable. In other words, you can pre-determine the id of the component you want focused.

The easiest case is when you know what the id would be, but it's also possible that something other than id is what determines focus such as order or position. Here's an example of how to apply focus to the last element in the NgFor list:

<ul>
  <li *ngFor="let item of items; last as isLast" >
    <mat-form-field>
      <input *ngIf="isLast; else noFocus" #usernameField type=number attr.id={{item.name}}>
    </mat-form-field>
  </li>
</ul>
<ng-template #noFocus>
  <input type=number attr.id={{item.name}}>
</ng-template>

@ViewChild('usernameField') usernameField: ElementRef;

ngAfterViewInit() {
  setTimeout(() => this.usernameField.nativeElement.focus());
}

Of course, the expression used in the NgIf can be anything including a simple value comparison such as:

<input *ngIf="item.name === 'usernameField'; else noFocus" #usernameField type=number attr.id={{item.name}}>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.