使输入成为焦点2/5

时间:2018-06-13 14:01:21

标签: angular angular5

点击后会显示输入元素(OnViewInit隐藏)。 我需要这个输入将在它出现时聚焦。当输入未被* ngIf(#inputElement2)隐藏时,它工作正常。

是否可以为#inputElement1实现它?

HTML:

<div class="container" *ngIf="isVisible">
  <input #inputElement1 placeholder="input element 1"/>
</div>


<input #inputElement2 placeholder="input element 2"/>

<div>
  <button (click)="toggleInput();">focus</button>
</div>

TS:

  isVisible = false ;
  @ViewChild("inputElement1") inputEl: ElementRef;
  @ViewChild("inputElement2") inputEl2: ElementRef;

  toggleInput() {
    this.isVisible = !this.isVisible;
    if(this.inputEl){
      this.inputEl.nativeElement.focus();
    }
    this.inputEl2.nativeElement.focus()
  }

2 个答案:

答案 0 :(得分:0)

toggleInput() {
    this.isVisible = !this.isVisible;
   setTimeout(()=> {
            if(this.inputEl){
              this.inputEl.nativeElement.focus();
            }
            this.inputEl2.nativeElement.focus();
    })
  }

答案 1 :(得分:0)

问题是 时调用焦点事件。因为您使用nativeElement(一种不安全且不可靠的方式),代码无法正常工作。

要使它像这样工作,您可以将其更改为:

  toggleInput() {
    this.isVisible = !this.isVisible;
  }

  ngAfterViewChecked() {
    if (this.isVisible) {
      this.inputEl.nativeElement.focus();
    } else {
      this.inputEl2.nativeElement.focus()
    }
  }

您必须实施AfterViewChecked生命周期钩子,即

export class MypComponent implements AfterViewChecked
相关问题