如何在angular2中使用[(ngModel)] div的contenteditable?

时间:2016-02-13 09:11:16

标签: angular ionic2 contenteditable

我正在尝试使用ngModel双向绑定div的可信输入内容,如下所示:

<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 ''

7 个答案:

答案 0 :(得分:72)

NgModel期望绑定元素具有value属性,div没有。这就是你得到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事件。您总是可以绑定到某些键盘事件。

答案 1 :(得分:11)

更新回答(2017-10-09)

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

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

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

其中post - 具有属性postTitle的对象。

首次,在ngOnInit()后从后端获取post后,我在我的组件中设置了this.postTitle = post.postTitle

答案 2 :(得分:9)

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

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

我使用\n将其调整为处理多行纯文本(<br> s而非white-space: pre-wrap s),并将其更新为使用keyup代替blur。请注意,此问题的某些解决方案使用的input事件尚未在contenteditable元素上的IE或Edge上受支持。

以下是代码:

<强>指令:

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进行测试。

答案 3 :(得分:7)

这里的another version基于@ 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;
  }
}

答案 4 :(得分:4)

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

OleDbException E_UNEXPECTED(0x8000FFFF)

我更喜欢将模板引用变量用于&#34; $ event&#34;东西。

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

答案 5 :(得分:1)

如果你绑定的是一个字符串,没有必要的事件,这是一个简单的解决方案。只需在表格单元格中输入一个文本框输入并绑定到该单元格即可。然后将文本框格式化为透明

HTML:

<tr *ngFor="let x of tableList">
    <td>
        <input type="text" [(ngModel)]="x.value" [ngModelOptions]="{standalone: true}">
    </td>
</tr>

答案 6 :(得分:1)

contenteditable 中,我通过 blur 事件和 innerHTML 实现了双向绑定属性。

.html中的

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

在.ts中:

getContent(innerText){
  this.content = innerText;
}