64

我正在尝试使用 ngModel 两种方式绑定 div 的 contenteditable 输入内容,如下所示:

<div id="replyiput" class="btn-input"  [(ngModel)]="replyContent"  contenteditable="true" data-text="type..." style="outline: none;"    ></div> 

但它不起作用并且发生错误:

EXCEPTION: No value accessor for '' in [ddd in PostContent@64:141]
app.bundle.js:33898 ORIGINAL EXCEPTION: No value accessor for ''
4

8 回答 8

117

NgModel期望被绑定的元素有一个value属性,而divs 没有。这就是你得到No value accessor错误的原因。

textContent您可以使用属性(而不是value)和事件来设置自己的等效属性和事件数据绑定input

import {Component} from 'angular2/core';
@Component({
  selector: 'my-app',
  template: `{{title}}
    <div contenteditable="true" 
     [textContent]="model" (input)="model=$event.target.textContent"></div>
    <p>{{model}}`
})
export class AppComponent {
  title = 'Angular 2 RC.4';
  model = 'some text';
  constructor() { console.clear(); }
}

Plunker

我不知道是否input所有浏览器都支持该事件contenteditable。您总是可以绑定到一些键盘事件。

于 2016-02-13T18:19:06.843 回答
17

更新答案(2017-10-09)

现在我有ng-contenteditable模块。它与 Angular 表单的兼容性。

旧答案(2017-05-11):就我而言,我可以简单地做到:

<div
  contenteditable="true"
  (input)="post.postTitle = $event.target.innerText"
  >{{ postTitle }}</div>

Where post- 它是具有属性的对象postTitle

第一次,在从后端ngOnInit()获取之后,我设置了我的组件。postthis.postTitle = post.postTitle

于 2017-05-11T10:09:23.583 回答
13

在这里工作 Plunkr http://plnkr.co/edit/j9fDFc,但下面的相关代码。


绑定和手动更新textContent对我不起作用,它不处理换行符(在 Chrome 中,在换行符后键入会将光标跳回开头)但我能够使用https中的 contenteditable 模型指令使其工作://www.namekdev.net/2016/01/two-way-binding-to-contenteditable-element-in-angular-2/

我使用 对其进行了调整以处理多行纯文本(带\ns,而不是<br>s)white-space: pre-wrap,并将其更新为使用keyup而不是blur. 请注意,此问题的某些解决方案使用IE 或 Edge元素尚不input支持的事件。contenteditable

这是代码:

指示:

import {Directive, ElementRef, Input, Output, EventEmitter, SimpleChanges} from 'angular2/core';

@Directive({
  selector: '[contenteditableModel]',
  host: {
    '(keyup)': 'onKeyup()'
  }
})
export class ContenteditableModel {
  @Input('contenteditableModel') model: string;
  @Output('contenteditableModelChange') update = new EventEmitter();

  /**
   * By updating this property on keyup, and checking against it during
   * ngOnChanges, we can rule out change events fired by our own onKeyup.
   * Ideally we would not have to check against the whole string on every
   * change, could possibly store a flag during onKeyup and test against that
   * flag in ngOnChanges, but implementation details of Angular change detection
   * cycle might make this not work in some edge cases?
   */
  private lastViewModel: string;

  constructor(private elRef: ElementRef) {
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['model'] && changes['model'].currentValue !== this.lastViewModel) {
      this.lastViewModel = this.model;
      this.refreshView();
    }
  }

  /** This should probably be debounced. */
  onKeyup() {
    var value = this.elRef.nativeElement.innerText;
    this.lastViewModel = value;
    this.update.emit(value);
  }

  private refreshView() {
    this.elRef.nativeElement.innerText = this.model
  }
}

用法:

import {Component} from 'angular2/core'
import {ContenteditableModel} from './contenteditable-model'

@Component({
  selector: 'my-app',
  providers: [],
  directives: [ContenteditableModel],
  styles: [
    `div {
      white-space: pre-wrap;

      /* just for looks: */
      border: 1px solid coral;
      width: 200px;
      min-height: 100px;
      margin-bottom: 20px;
    }`
  ],
  template: `
    <b>contenteditable:</b>
    <div contenteditable="true" [(contenteditableModel)]="text"></div>

    <b>Output:</b>
    <div>{{text}}</div>

    <b>Input:</b><br>
    <button (click)="text='Success!'">Set model to "Success!"</button>
  `
})
export class App {
  text: string;

  constructor() {
    this.text = "This works\nwith multiple\n\nlines"
  }
}

到目前为止,仅在 Linux 上的 Chrome 和 FF 中进行了测试。

于 2016-12-21T01:45:51.437 回答
10

这是另一个版本,基于@tobek 的回答,它也支持 html 和粘贴:

import {
  Directive, ElementRef, Input, Output, EventEmitter, SimpleChanges, OnChanges,
  HostListener, Sanitizer, SecurityContext
} from '@angular/core';

@Directive({
  selector: '[contenteditableModel]'
})
export class ContenteditableDirective implements OnChanges {
  /** Model */
  @Input() contenteditableModel: string;
  @Output() contenteditableModelChange?= new EventEmitter();
  /** Allow (sanitized) html */
  @Input() contenteditableHtml?: boolean = false;

  constructor(
    private elRef: ElementRef,
    private sanitizer: Sanitizer
  ) { }

  ngOnChanges(changes: SimpleChanges) {
    if (changes['contenteditableModel']) {
      // On init: if contenteditableModel is empty, read from DOM in case the element has content
      if (changes['contenteditableModel'].isFirstChange() && !this.contenteditableModel) {
        this.onInput(true);
      }
      this.refreshView();
    }
  }

  @HostListener('input') // input event would be sufficient, but isn't supported by IE
  @HostListener('blur')  // additional fallback
  @HostListener('keyup') onInput(trim = false) {
    let value = this.elRef.nativeElement[this.getProperty()];
    if (trim) {
      value = value.replace(/^[\n\s]+/, '');
      value = value.replace(/[\n\s]+$/, '');
    }
    this.contenteditableModelChange.emit(value);
  }

  @HostListener('paste') onPaste() {
    this.onInput();
    if (!this.contenteditableHtml) {
      // For text-only contenteditable, remove pasted HTML.
      // 1 tick wait is required for DOM update
      setTimeout(() => {
        if (this.elRef.nativeElement.innerHTML !== this.elRef.nativeElement.innerText) {
          this.elRef.nativeElement.innerHTML = this.elRef.nativeElement.innerText;
        }
      });
    }
  }

  private refreshView() {
    const newContent = this.sanitize(this.contenteditableModel);
    // Only refresh if content changed to avoid cursor loss
    // (as ngOnChanges can be triggered an additional time by onInput())
    if (newContent !== this.elRef.nativeElement[this.getProperty()]) {
      this.elRef.nativeElement[this.getProperty()] = newContent;
    }
  }

  private getProperty(): string {
    return this.contenteditableHtml ? 'innerHTML' : 'innerText';
  }

  private sanitize(content: string): string {
    return this.contenteditableHtml ? this.sanitizer.sanitize(SecurityContext.HTML, content) : content;
  }
}
于 2017-06-28T12:45:03.020 回答
5

我已经摆弄了这个解决方案,现在将在我的项目中使用以下解决方案:

<div #topicTitle contenteditable="true" [textContent]="model" (input)="model=topicTitle.innerText"></div>

我更喜欢使用模板引用变量而不是“$event”的东西。

相关链接: https ://angular.io/guide/user-input#get-user-input-from-a-template-reference-variable

于 2017-11-06T21:03:50.753 回答
2

contenteditable中,我借助blur事件和innerHTML属性实现了两种方式的绑定。

在 .html 中:

<div placeholder="Write your message.."(blur)="getContent($event.target.innerHTML)" contenteditable [innerHTML]="content"></div>

在 .ts 中:

getContent(innerText){
  this.content = innerText;
}
于 2020-05-27T11:05:33.080 回答
0

如果您绑定的是字符串,则这是一个简单的解决方案,不需要事件。只需在表格单元格内放置一个文本框输入并绑定到该单元格。然后将文本框格式化为透明

HTML:

<tr *ngFor="let x of tableList">
    <td>
        <input type="text" [(ngModel)]="x.value" [ngModelOptions]="{standalone: true}">
    </td>
</tr>
于 2018-06-08T19:19:33.717 回答
0

对我来说,使用 javascript 就足够了,没有 ts 对象。HTML:

 <div
        id="custom-input"
        placeholder="Schreiben..."
</div>

TS:

  • 获取输入值:document.getElementById("custom-input").innerHTML

  • 设置输入值:document.getElementById("custom-input").innerHTML = "myValue"

一切都很完美。我被迫使用 div 而不是 ionic ion-textarea,因为我遇到了自动调整大小的问题。使用 ion-textarea 我只能使用 js 进行自动调整大小。现在我用 CSS 自动调整大小,我认为这更好。

于 2020-01-20T13:50:05.640 回答