我使用的是Angular。
我的代码。
<div contentEditable="true" attr.placeholder="{{placeholder}}"
[textContent]="model"
(input)="[model=$event.target.textContent,inputed($event)]">
</div>
我试图建立一个响应式网站。上面的组件在网页版中工作得很好,甚至当我用google chrome在不同尺寸的网页上测试时也是如此。当我尝试在移动设备上使用safari浏览器时,问题来了。输入光标不移动,文字出现在它的前面。文字出现在后面。
例如,如果我输入 你好,世界。 看来 .dlrow olleH. 光标停留在最左边。
如果我把 model=$event.target.textContent
即使在手机浏览器上也能正常工作。有什么办法可以让它正常工作,而不需要删除这段代码?
我已经找到了问题的解决方案。
老问题代码。
HTML:
<div contentEditable="true" attr.placeholder="{{placeholder}}"
[textContent]="model"
(input)="inputed($event)">
</div>
Typescript文件。
@Input() model = '';
inputed(event){
this.model = event.target.textContent;
this.propagateChange(this.model.trim());
}
新代码,解决方案
HTML。
<div contenteditable="true" attr.placeholder="{{placeholder}}"
[textContent]="model"
(input)="inputed($event)" >
</div>
类型稿文件
@Input() model = '';
inputed(event){
this.propagateChange(event.target.textContent);
}
在typecript文件中还有更多的代码,允许该组件在反应式表单中作为表单输入。以下是typecript文件的完整代码。
import { Component, OnInit, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'custom-textarea',
templateUrl: './custom-textarea.component.html',
styleUrls: ['./custom-textarea.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => CustomTextareaComponent),
}
]
})
export class CustomTextareaComponent implements ControlValueAccessor, OnInit {
@Input() placeholder:string = "";
propagateChange = (_: any) => {};
writeValue(obj: any): void {
if (obj !== undefined) {
this.model = obj;
}
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void {
// We don’t want to do anything at this event,
// so we can implement the interface with an empty function.
}
setDisabledState?(isDisabled: boolean): void {
// We don’t want to do anything at this event,
// so we can implement the interface with an empty function.
}
constructor() { }
ngOnInit() { }
@Input() model = '';
inputed(event){
this.propagateChange(event.target.textContent);
}
}