每当启用时将焦点设置在按钮上
set focus on button whenever it gets enabled
在我的 Angular 8 应用程序中,我试图在 mat 按钮启用后立即将焦点设置在它上。启用按钮发生在收到来自服务的响应并验证了几个条件之后。 是我的老问题。
但是由于某种原因,当我在我的原始代码中使用时它不起作用。所以我正在寻找类似自动对焦指令的选项,它可以在启用按钮时设置焦点。有可能实现吗?
您可以 ViewChild
您的按钮元素:
export class InputErrorsExample {
@ViewChild('search', { static: true }) btn: HTMLButtonElement;
city = new FormControl('');
search: boolean = false;
constructor(private http: HttpClient) {}
fetchCityDetails() {
this.http
.get('https://countriesnow.space/api/v0.1/countries/population/cities')
.subscribe(data => {
if (data) {
this.search = true;
this.btn.focus();
}
});
}
}
但您还必须在 HTML
中提供适当的标签 #search
<button tabindex="0" #search mat-raised-button color="primary" [disabled] = "!search">Search</button>
通过对 Beka 提供的答案进行以下修改,我能够将焦点设置在按钮上
export class InputErrorsExample {
@ViewChild('search', {read: ElementRef, static: false}) btn: ElementRef; // to access button in ts
city = new FormControl('');
search: boolean = false;
constructor(private http: HttpClient) {}
fetchCityDetails() {
this.http
.get('https://countriesnow.space/api/v0.1/countries/population/cities')
.subscribe(data => {
if (data) {
this.btn.nativeElement.disabled = false ;
this.btn.nativeElement.focus();
}
});
}
}
在我的 Angular 8 应用程序中,我试图在 mat 按钮启用后立即将焦点设置在它上。启用按钮发生在收到来自服务的响应并验证了几个条件之后。
您可以 ViewChild
您的按钮元素:
export class InputErrorsExample {
@ViewChild('search', { static: true }) btn: HTMLButtonElement;
city = new FormControl('');
search: boolean = false;
constructor(private http: HttpClient) {}
fetchCityDetails() {
this.http
.get('https://countriesnow.space/api/v0.1/countries/population/cities')
.subscribe(data => {
if (data) {
this.search = true;
this.btn.focus();
}
});
}
}
但您还必须在 HTML
中提供适当的标签#search
<button tabindex="0" #search mat-raised-button color="primary" [disabled] = "!search">Search</button>
通过对 Beka 提供的答案进行以下修改,我能够将焦点设置在按钮上
export class InputErrorsExample {
@ViewChild('search', {read: ElementRef, static: false}) btn: ElementRef; // to access button in ts
city = new FormControl('');
search: boolean = false;
constructor(private http: HttpClient) {}
fetchCityDetails() {
this.http
.get('https://countriesnow.space/api/v0.1/countries/population/cities')
.subscribe(data => {
if (data) {
this.btn.nativeElement.disabled = false ;
this.btn.nativeElement.focus();
}
});
}
}