Фокус при нажатии на кнопку, открывающую вход

Как мне сосредоточиться на вводе, который сначала скрыт, но открывается по нажатию кнопки? Атрибут автофокуса работает только в первый раз, а 'nativeElement' не определено. На jQuery все просто, но мне нужно обойтись без него.

<input type="text" *ngIf="isVisible" #test autofocus>
<button (click)="testAction()">Test</button>

@ViewChild('test') test: ElementRef;
isVisible = false;
testAction() {
this.isVisible = !this.isVisible;
this.test.nativeElement.focus();
}

person Oleg Zinchenko    schedule 30.03.2018    source источник
comment
Вместо *ngIf используйте [hidden]. Использование *ngIf предотвратит рендеринг элемента DOM, поэтому вы не можете сфокусировать его, поскольку он не существует.   -  person Hoyen    schedule 30.03.2018


Ответы (2)


Я сделал что-то похожее на то, что вы просите; однако я сделал это с помощью директивы:

import { Directive, ElementRef, Input, OnChanges } from '@angular/core';

@Directive({
  selector: '[afnFocus]'
})
export class FocusDirective implements OnChanges {
  @Input() afnFocus: boolean;

  constructor(private el: ElementRef) { }

  ngOnChanges() {
    if (this.afnFocus) {
      this.el.nativeElement.focus();
    }
  }

}

Затем поместите директиву в элемент и привяжите ее к логическому значению isVisible.

person Andrew Lobban    schedule 30.03.2018

Другой метод

testAction() {
 this.isVisible = !this.isVisible;

 if (this.test && this.test.nativeElement) {
    setTimeout(() => this.test.nativeElement.focus(), 800);
 }
}
person Oleg Zinchenko    schedule 02.04.2018