yantrab
yantrab

Reputation: 2662

How to set focus on show, where ngIf bind change to true?

I am trying to do editable cell:

  <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">
    <div style="height: 50px; width: 100%" (click)="inEdit=true" (blur)="inEdit=false">
    <div *ngIf="!inEdit">
      {{row[field.property]}}
    </div>
    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]">
    </mat-form-field>
    </div>
  </ng-template>

It is working well, the final thing that I need to do , is to set focus on input, that let the user to type.

So, there is a way to do that, without exclude the input to component?

something like (onShow)="this.focus()" ?

Upvotes: 1

Views: 199

Answers (2)

Yash Rami
Yash Rami

Reputation: 2327

You can use ElementRef here is the example

HTML

 <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">
    <div style="height: 50px; width: 100%" (click)="inEdit=true" (blur)="inEdit=false">
    <div *ngIf="!inEdit">
      {{row[field.property]}}
    </div>
    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]" #inputRef>
    </mat-form-field>
    </div>
  </ng-template>

TS

@ViewChild('inputRef') inputRefData : ElementRef

customFocus() {
  this.inputRefData.nativeElement.focus();
}

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try autofocus :

<mat-form-field *ngIf="inEdit" class="example-full-width">
  <input matInput [(ngModel)]="row[field.property]" autofocus>
</mat-form-field>

Upvotes: 2

Related Questions