我有以下div:
<div
contenteditable="true"
(input)="onInput($event)"
(keyup)="onKeyUp($event)"
>
</div>
输入事件没有给我任何信息
onKeyUp 事件始终返回 event.keyCode === 229,与 event.which 相同。无论如何,我可以在安卓设备上按下正确的键代码吗?
你可以编写一个content-editable-form.directive,如下所示,以触发事件:
import {
Directive,
ElementRef,
Renderer2,
HostListener,
forwardRef,
Input,
OnInit,
HostBinding
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[contenteditable]',
providers:
[
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => ContentEditableFormDirective), multi: true }
]
})
export class ContentEditableFormDirective implements ControlValueAccessor {
@HostBinding('attr.contenteditable') enabled = true;
private onChange: (value: string) => void;
private onTouched: () => void;
private removeDisabledState: () => void;
constructor(private elementRef: ElementRef, private renderer: Renderer2) { }
@HostListener('input') onInput(): void {
this.onChange(this.elementRef.nativeElement.innerText);
}
@HostListener('blur') onBlur(): void {
this.onTouched();
}
writeValue(value: string): void {
this.renderer.setProperty(this.elementRef.nativeElement, 'innerText', value || '');
}
registerOnChange(onChange: (value: string) => void): void {
this.onChange = onChange;
}
registerOnTouched(onTouched: () => void): void {
this.onTouched = onTouched;
}
setDisabledState(disabled: boolean): void {
this.enabled = !disabled;
}
}
.html:
<label><input type="checkbox" [(ngModel)]="enabled"> Enabled</label>
<div contenteditable="true" [(ngModel)]="text" [disabled]="!enabled" #control="ngModel"></div>
<pre [innerHTML]="text"></pre>
演示。