通过在角度角度的模板级别上的交互来更新“自动对焦”属性

Ber*_*ard 3 html angular

autofocus与Angular合作时在属性方面存在问题。详细地讲,我<form><input type="text">顶部有一个,最初是根据条件集中的。

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

可以正常运行(Chrome)。

然后,该表单连续,并在由所控制的两个选项之间进行选择<input type="radio">

一旦做出选择,就会显示一个相应的元素,然后应获取autofocus

但这并没有发生,我也不知道原因。

准备了一个带有有效示例stackblitz,但主要是下面的标记无法按预期工作

<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>
Run Code Online (Sandbox Code Playgroud)

Con*_*Fan 5

如果签入开发工具(F12工具),您将看到新的输入控件实际上获得了autofocus属性,但没有获得焦点。那是因为页面加载时将autofocus焦点放在元素。您的情况是,当新元素变为可见时,页面已经加载。

相反,您可以通过编程将焦点设置在新的input元素上。为此,您可以为具有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">
Run Code Online (Sandbox Code Playgroud)

并通过ViewChildrenQueryList.changes事件监视这些元素的存在。每当输入元素之一变为可见时,就将焦点设置在它上面:

@ViewChildren("inputElement") inputElements: QueryList<ElementRef>;

ngAfterViewInit() {
  this.inputElements.changes.subscribe(() => {
    this.inputElements.last.nativeElement.focus();
  });
}
Run Code Online (Sandbox Code Playgroud)

有关演示,请参见此堆叠闪电战