Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

angular - How to set focus on element with binding?

In Angular2 how can I set binding on element focus. I don't want to set it with elementRef. I think in AngularJS there is ngFocus directive In Angular2 there is no such directive

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Renderer service is now deprecated (as of Angular 4.x) The new Renderer2 service doesn't have the invokeElementMethod. What you can do is to get a reference to the element like this:

const element = this.renderer.selectRootElement('#elementId');

And then you can use that to focus on that element like so:

element.focus();

More on how selectRootElement works here:

EDIT:

If the element doesn't get focused the common issue is that the element is not ready. (eg.: disabled, hidden etc.). You can do this:

setTimeout(() => element.focus(), 0);

This will create a macrotask that will run in the next VM turn, so if you enabled the element the focus will run properly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...