Angular2 - 如何访问尚未呈现的子输入元素?

use*_*043 5 angular

例如,我的模板看起来像 -

<div #parent>
    <button (click)="showInput()"> Show </button>
    <input #inp *ngIf="showInpField" />
</div>
Run Code Online (Sandbox Code Playgroud)

这就是我的组件的样子:

import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
  selector: 'some-component',
  templateUrl: './template.html',
})
export class SomeComponent {
    @ViewChild('inp') inpField: any;
    showInpField = false;
    constructor() {}
    showInput(){
        this.showInpField = true;
        // This doesn't work
        this.qaTitle.inpField.focus();
    }   
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,焦点不起作用,因为输入元素尚未呈现。我意识到在那条线上使用超时会起作用,但不知何故,我觉得这不是一个好方法。

我想不知何故我已经检测到父 div 内部的变化,并且在那个事件上我应该做焦点操作。我该怎么做?我觉得 QueryList 可能会有所帮助,但我不知道在这种情况下如何使用它!

yur*_*zui 6

这可以工作

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="toggleInput()"> {{ showInpField ? 'Hide' : 'Show'}} </button>
      <input #inp *ngIf="showInpField" />
  </div>
  `
})
export class AppComponent { 
  @ViewChildren('inp', { read: ElementRef }) elemRefs: QueryList<ElementRef>;

  showInpField = false;

  constructor(private renderer: Renderer){}

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

  ngAfterViewInit() {
    this.elemRefs.changes.subscribe(item => {
      if(!this.elemRefs.length) return;

      this.renderer.invokeElementMethod(this.elemRefs.first.nativeElement, 'focus');
    })
  } 
}
Run Code Online (Sandbox Code Playgroud)

Plunker 示例