0

I have the problem, that I need the focus on the clicked column field in my table. I always have to click two times on the field to modify the content in the input field.

HTML:

<table mat-table [dataSource]="dataSource">
  <ng-container matColumnDef="ID">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let elem" (click)="editCell(elem.ID)" (keydown.enter)="editCell($event.keyCode)"> 
      <span *ngIf="!editable"> {{elem.ID}} </span>
      <mat-form-field *ngIf="editable">
        <input matInput [(ngModel)]="elem.ID">
      </mat-form-field>
    </td>
  </ng-container>
  ...
</table>

Component:

editCell(item: any): void {
    console.log('item: ', item);

    if(!this.editable) {
      this.editable = !this.editable;
    } else if(item === 13) {
      this.editable = !this.editable;
    }
}

I read in other threads something about the template reference variable and the method .focus() but it doesn't work for me.

Can anyone help me?

yuro
  • 2,189
  • 6
  • 40
  • 76

1 Answers1

1

Try this

(focus)="editCell('focusin')" (focusout)="editCell('focus out')"
Er Abdul Meman
  • 163
  • 1
  • 9
  • I don't understand your approach. What can I do with the string? – yuro Mar 19 '19 at 12:47
  • (focus)="this.editable = false" && (focusout)="this.editable = true" – Er Abdul Meman Mar 19 '19 at 13:15
  • Try this you don't need function I just mentioned event that can help you – Er Abdul Meman Mar 19 '19 at 13:16
  • No, that's not the expected solution. first the `span`-Tag is displayed. When you click in a cell then the span-tag will be hidden and the input field is displayed. So, After displaying the input field the focus has to be on this input field after the click! – yuro Mar 19 '19 at 14:21