Having a problem regarding the autofocus
attribute in cooperation with Angular. In detail I have a with an
If you check in the development tools (F12 tools), you will see that the new input control actually gets the autofocus
attribute, but it does not get the focus. That is because autofocus
sets the focus on an element when the page loads. In your case, the page is already loaded when the new element becomes visible.
What you can do instead is to set the focus programmatically on the new input element. In order to do that, you can define a common template reference variable for the two input elements having an ngIf
condition:
and monitor the presence of these elements with ViewChildren
and the QueryList.changes
event. Each time one of the input element becomes visible, you set the focus on it:
@ViewChildren("inputElement") inputElements: QueryList;
ngAfterViewInit() {
this.inputElements.changes.subscribe(() => {
this.inputElements.last.nativeElement.focus();
});
}
See this stackblitz for a demo.