在valueChanges订阅回调中将焦点动态设置回元素可以通过以下步骤实现:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
<input type="text" [formControl]="myControl">
`
})
export class ExampleComponent {
myControl = new FormControl();
}
@Component({
selector: 'app-example',
template: `
<input #inputElement type="text" [formControl]="myControl">
`
})
export class ExampleComponent {
@ViewChild('inputElement') inputElement: ElementRef;
myControl = new FormControl();
}
import { Component, ViewChild, ElementRef, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-example',
template: `
<input #inputElement type="text" [formControl]="myControl">
`
})
export class ExampleComponent implements OnInit {
@ViewChild('inputElement') inputElement: ElementRef;
myControl = new FormControl();
ngOnInit() {
this.myControl.valueChanges.subscribe(() => {
this.inputElement.nativeElement.focus();
});
}
}
这样,每当输入框的值发生变化时,焦点就会动态地设置回输入框元素。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云