与Angular合作时,autofocus
属性存在问题。详细地说,我有一个<form>
,其顶部是<input type="text">
,最初是由条件集中的。
<input [attr.autofocus]="selection===-1"
[(ngModel)]="myForm.firstInpElem"
name="firstInpElem"
placeholder="firstInpElem">
此功能正常运行(Chrome)。
然后,该窗体连续,并在<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>
答案 0 :(得分:4)
如果签入开发工具(F12工具),您将看到新的输入控件实际上获得了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">
,并通过ViewChildren
和QueryList.changes
事件监视这些元素的存在。每当输入元素之一变为可见时,就将焦点设置在该输入元素上:
@ViewChildren("inputElement") inputElements: QueryList<ElementRef>;
ngAfterViewInit() {
this.inputElements.changes.subscribe(() => {
this.inputElements.last.nativeElement.focus();
});
}
有关演示,请参见this stackblitz。
答案 1 :(得分:0)
另一个选项是隐藏输入(不使用* ngIf else display.style)和引用变量 参见https://stackblitz.com/edit/angular-sbc4pp?file=src%2Fapp%2Fapp.component.html
<label>
<input [ngModel]="selection" (change)="change(second,1)"
name="radioInpElem"
type="radio"
[value]="1">
Option 1
</label>
<br>
<label>
<input [ngModel]="selection" (change)="change(third,2)"
name="radioInpElem"
type="radio"
[value]="2">
Option 2
</label>
<input #second [style.display]="selection===1?'inherit':'none'"
[(ngModel)]="myForm.secondInpElem"
name="secondInpElem"
placeholder="secondInpElem">
<input #third [style.display]="selection===2?'inherit':'none'"
[(ngModel)]="myForm.thirdInpElem"
name="thirdInpElem"
placeholder="thirdInpElem">
您的功能更改类似
change(element:any,index:number)
{
this.selection=index;
setTimeout(()=>{element.focus()},0);
}