我在 div
中有许多 input
框,我需要以编程方式聚焦其中一个。
怎么做?
是这样的:
<div>
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
<input type="text" name="txt4" />
<input type="text" name="txt5" />
<input type="text" name="txt6" />
</div>
<button (click)="selectSample()" />
selectSample() {
?????????('txt3').focus();
console.log('Button pressed, txt3 has been selected');
}
最佳答案
@Component({
selector: 'my-app',
template: `
<div>
<input #input type="text" name="txt1" />
<input #input type="text" name="txt2" />
<input #input type="text" name="txt3" />
<input #input type="text" name="txt4" />
<input #input type="text" name="txt5" />
<input #input type="text" name="txt6" />
</div>
<button (click)="selectSample()">click</button>
`
})
export class App {
@ViewChildren('input') inputs;
selectSample() {
// console.debug(this.inputs.toArray().find((e) => {
// return e.nativeElement.getAttribute('name') == 'txt3';
//}).nativeElement.value);
this.inputs.toArray().find((e) => {
return e.nativeElement.getAttribute('name') == 'txt3';
}).nativeElement.focus();
}
}
关于angular - 聚焦 <input> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36329658/