在Android上,当使用Angular构建应用程序时,存在一个问题,即“下一步”按钮无法聚焦到Custom ControlValueAccesor。要解决这个问题,需要将控件手动聚焦。以下是解决该问题的示例代码:
(1)创建一个控件的示例,例如textarea
import { Component, forwardRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
const CUSTOM_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyInputComponent), multi: true, };
@Component({
selector: 'app-my-input',
template: ,
providers: [CUSTOM_VALUE_ACCESSOR],
})
export class MyInputComponent implements ControlValueAccessor {
public onChange: (_: any) => void = noop;
public onTouched: () => void = noop;
writeValue(value: any): void { const normalizedValue = value === null ? '' : value; this.myInput.nativeElement.value = normalizedValue; }
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
setDisabledState(isDisabled: boolean): void { this.myInput.nativeElement.disabled = isDisabled; } }
(2)使用以下代码强制聚焦:
import { Component, forwardRef } from '@angular/core'; import { MyInputComponent } from './my-input.component';
@Component({
selector: 'app-root',
template:
,
})
export class AppComponent {
public myValue: string;
constructor(private readonly myInput: MyInputComponent) {}
public onClick(): void { this.myInput.writeValue(this.myValue); this.myInput.myInput.nativeElement.focus(); } }
通过在按钮上添加click事件,并在click事件处理程序中使用手动焦点强制聚焦,在Android上解决Angular中Custom ControlValueAccesor的下一步按钮聚焦问题。