【问题标题】:contentEditable="true": Text appearing infront of input cursorcontentEditable="true":文本出现在输入光标的前面
【发布时间】:2020-09-16 03:50:01
【问题描述】:

我正在使用角度。

我的代码:

<div contentEditable="true" attr.placeholder="{{placeholder}}" 
    [textContent]="model"
    (input)="[model=$event.target.textContent,inputed($event)]">
</div>

我正在尝试建立一个响应式网站。上面的组件在网络版本中运行良好,即使我使用谷歌浏览器在网络上测试不同尺寸的它。当我尝试使用 safari 浏览器在移动设备中使用表单时,问题就出现了。输入光标不移动,文本出现在其前面。文本向后显示。

例如,如果我输入 Hello world.,它会显示为 .dlrow olleH。光标停留在最左边。

如果我删除 model=$event.target.textContent,即使在移动浏览器上也能正常工作。有没有办法让它正常工作而不必删除这段代码?

【问题讨论】:

  • 您是否尝试过使用双向绑定[(ngModel)]="model" 代替?
  • @ConnorsFan 我正在以反应形式使用该组件,因此 ngModel 无济于事。

标签: html angular forms dom


【解决方案1】:

我找到了解决问题的方法。

老问题代码:

HTML:

<div contentEditable="true" attr.placeholder="{{placeholder}}" 
    [textContent]="model"
    (input)="inputed($event)">
</div>

打字稿文件:

@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);
  }

打字稿文件中有更多代码允许将组件用作响应式表单中的表单输入。以下是打字稿文件的完整代码。

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);
  }

}

【讨论】:

    猜你喜欢
    • 2015-10-16
    • 2021-03-03
    • 2014-07-01
    • 2014-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多