-->

Angular 4 set the focus in the dynamic generated t

2019-07-19 18:18发布

问题:

I have the dynamically generated textbox as below.

<tr *ngFor="let item of data; let in=index">
    <td>
                        <input #unitNumber type="text" name="workPerformed-workcode-{{in}}" [(ngModel)] = "item.unitnumber" >
                      </td>
<td> <!-- Search option is given to chose the unit number----></td>
</tr>

Here, the search option is given to choose the unit number, if it has been chosen, then the corresponding textbox will be focused on using viewChildran.

My try is

@ViewChildren('unitNumber') enteredUnitNumbers;

// for searching, I have used the material dialog box
const dialogRef = this.dialog.open(SearchEquipmentComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(
      <!-- HERE I NEED TO DO THE FOCUS ON PARTICULAR TEXTBOX ---->
     // console.log(this.enteredUnitNumbers.toArray().map(x => x))
});

Above console.log shows undefined. My need is that once dialog box is closed the corresponding unit number textbox should be focused.

Kindly give solutions

回答1:

The following should do it:

enteredUnitNumbers.toArray()[0].nativeElement.focus();

Replace 0 with the index of the desired input.