与角度相关的autofocus属性有问题。具体来说,我有一个<form>顶部有一个<input type="text">的,它最初由一个条件聚焦。

<input [attr.autofocus]="selection===-1"
       [(ngModel)]="myForm.firstInpElem"
       name="firstInpElem"
       placeholder="firstInpElem">

这是按预期工作(铬)。
然后,表单在<input type="radio">控制的两个选项之间连续进行选择。
一旦做出选择,就会显示相应的元素,然后应该得到autofocus
但那不是真的,我不明白为什么。
准备了一个stackblitz with a working example但主要是下面的标记,它不能按预期工作
<h1>Forms example</h1>

<form>

  <pre>Condition to focus "firstInpElem" is {{selection===1|json}}</pre>

  <p>This input element is autofocussed on page load</p>

  <p>
    <input [attr.autofocus]="selection===-1"
           [(ngModel)]="myForm.firstInpElem"
           name="firstInpElem"
           placeholder="firstInpElem">
  </p>

  <p>
    Provide one of both information:<br>

    <label>
      <input [(ngModel)]="selection"
             name="radioInpElem"
             type="radio"
             [value]="1">
             Option 1
    </label>
    <br>

    <label>
      <input [(ngModel)]="selection"
             name="radioInpElem"
             type="radio"
             [value]="2">
             Option 2
    </label>

  </p>

  <pre>Condition to focus "secondInpElem" is {{selection===1|json}}</pre>
  <pre>Condition to focus "thirdInpElem" is {{selection===2|json}}</pre>
  <p>


  <input *ngIf="selection===1"
        [attr.autofocus]="selection===1"
        [(ngModel)]="myForm.secondInpElem"
        name="secondInpElem"
        placeholder="secondInpElem">



  <input *ngIf="selection===2"
          [attr.autofocus]="selection===2"
          [(ngModel)]="myForm.thirdInpElem"
          name="thirdInpElem"
          placeholder="thirdInpElem">
  </p>
</form>


<pre>{{myForm|json}}</pre>

最佳答案

如果签入开发工具(f12 tools),您将看到新的输入控件实际上获得了autofocus属性,但没有获得焦点。这是因为autofocus将焦点设置在元素when the page loads上。在您的例子中,当新元素变为可见时,页面已经加载。
您可以改为以编程方式将焦点设置在新的输入元素上。为此,可以为具有ngIf条件的两个输入元素定义公共模板引用变量:

<input #inputElement *ngIf="selection === 1"
      [(ngModel)]="myForm.secondInpElem"
      name="secondInpElem"
      placeholder="secondInpElem">

<input #inputElement *ngIf="selection === 2"
        [(ngModel)]="myForm.thirdInpElem"
        name="thirdInpElem"
        placeholder="thirdInpElem">

并用ViewChildrenQueryList.changes事件监视这些元素的存在。每次某个输入元素变为可见时,都会将焦点设置在它上:
@ViewChildren("inputElement") inputElements: QueryList<ElementRef>;

ngAfterViewInit() {
  this.inputElements.changes.subscribe(() => {
    this.inputElements.last.nativeElement.focus();
  });
}

有关演示,请参见this stackblitz

10-06 11:46