yantrab
yantrab

Reputation: 2652

autofocus not working after remove and adding again to the dom

I trying to set focus on show:

<div>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <div *ngIf="!inEdit">
      bla
    </div>
    <mat-form-field *ngIf="inEdit">
      <input (blur)="inEdit=false" 
      autofocus matInput >
    </mat-form-field>
  </div>
</div>

it is work only on first click.

stackbliz

Upvotes: 2

Views: 613

Answers (2)

Adrita Sharma
Adrita Sharma

Reputation: 22213

You can programmatically call a focus method of HTML element whenever you need!

Try this:

Template:

<div>
   <button mat-raised-button color="primary" (click)="inEdit=true;focus()">Edit</button>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <mat-form-field *ngIf="inEdit">
      <input #ref matInput >    
    </mat-form-field>
  </div>
</div>

TS:

import {Component, ViewChild, ElementRef } from '@angular/core';


@Component({
  selector: 'input-overview-example',
  styleUrls: ['input-overview-example.css'],
  templateUrl: 'input-overview-example.html',
})
export class InputOverviewExample {

  @ViewChild("ref",null) refField: ElementRef;

  focus(): void {
    setTimeout(() => {
      this.refField.nativeElement.focus();
    }, 100);
  }
}

Upvotes: 3

Prathmesh Nikam
Prathmesh Nikam

Reputation: 11

We can achieve all DOM related operations in Angular using @ViewChild decorator whic comes from angular core.

Related Template

HTML :

<input type="text" #inputName>

Component :

import { Component,AfterViewInit,ViewChild ElementRef} from '@angular/core';
... 

@ViewChild('inputName') inputEl:ElementRef;

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

Using this ElementRef we can do dynamic DOM(Component) Rendering.

Note:

Make sure before going to use ElememntRef,All DOM is rendered in local browser

Upvotes: 0

Related Questions