Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus to an element

I have an async HTTP call and want to set a focus to an error element in a template if the async call results in an error.

  • One way can be to inject the ElementRef and then use jQuery to access element and call focus() method on it.

class MyComponent {
   
    constructor(private element: ElementRef) {}

    doAsync() {
        // do something async

        $(this.element.nativeElement).find('.error').focus();
    }
}
  • Another way may be to create a directive, that binds to a property on model and calls focus() method on a host element.

How good is to include/use JQuery in angular 2?

Also, I believe the way Angular is meant to work (MV*) is to 'modify model to which view reacts'. So, which one is correct way to do it?

like image 626
EagerToLearn Avatar asked Jan 03 '23 21:01

EagerToLearn


1 Answers

Let's try this in your focus component

 import --> AfterViewInit

 export class YourComponent implements AfterViewInit {
   @ViewChild('err') vc: any;


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

use this component html

<div #err class="alert alert-danger>{{errorPrompt}}</div>
like image 187
yala ramesh Avatar answered Jan 21 '23 07:01

yala ramesh