EagerToLearn
EagerToLearn

Reputation: 857

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.

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

    doAsync() {
        // do something async

        $(this.element.nativeElement).find('.error').focus();
    }
}

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?

Upvotes: 4

Views: 20720

Answers (4)

yala ramesh
yala ramesh

Reputation: 3362

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>

Upvotes: 12

a3uge
a3uge

Reputation: 417

Not entirely sure what kind of element '.error' is, but you could try something like this:

class MyComponent {

    constructor(private renderer: Renderer2) { }

    doAsync() {
        // do something async

        setTimeout(() => {
            const element = this.renderer.selectRootElement('.error');
            if (element) {
                element.focus();
            }
        }, 200);
    }

}

I've found setTimeout is sometimes necessary if the element is nested in an *ngIf. Although not the cleanest solution, it's at least better than including jquery. You could also define your own directive for an autofocus reference.

Upvotes: 1

Joel Richman
Joel Richman

Reputation: 1934

In the result of your async function set a property on the component to show or hide the error message.

class MyComponent {

    hasErrors = false;
    errorPrompt = ""; 

    constructor() {}

    doAsync() {
        // do something async
        this.hasErrors = true;
        this.errorPrompt = "Fix the errors.";
    }
}

In the mark up:

<div class="alert alert-danger" *ngIf="hasErrors">{{errorPrompt}}</div>

Upvotes: 0

alehn96
alehn96

Reputation: 1393

You can use angular directive of class:

<component1 [ngClass]="{focusClass: setFocus() }"></component1>

if setFocus() return true active the class that put focus in the tag

Upvotes: -4

Related Questions