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

Kim*_*ong 48 contenteditable ionic2 angular

我试图使用ngModel双向绑定div的contenteditable输入内容,如下所示:

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

但它无法正常工作并发生错误:

EXCEPTION: No value accessor for '' in [ddd in PostContent@64:141]
app.bundle.js:33898 ORIGINAL EXCEPTION: No value accessor for ''
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 86

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(); }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

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

  • 无论用于触发model = $ event.target.textContent的事件如何,这当前在Firefox和Edge上都无法正常工作.键入时,光标始终设置为索引0.你应该知道这一点. (4认同)
  • 大家好,有人知道怎么整理所以光标索引不能一直设置为0吗? (4认同)
  • 目前这仅对向后输入有用 (3认同)
  • @KimWong,我提供的Plunker 中的`model` var 肯定会发生变化。这就是为什么我将 `{{model}}` 放在视图/模板中,以便我们在编辑 div 时可以看到它的变化。 (2认同)

ktr*_*yak 13

更新的答案(2017-10-09):

现在我有了ng-contenteditable模块.它与Angular形式的兼容性.

旧答案(2017-05-11):在我的情况下,我可以很简单地做:

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

在哪里post- 它是财产的对象postTitle.

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


tob*_*bek 10

在这里工作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.请注意,此问题的某些解决方案使用inputIE或Edge上不支持的事件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
  }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

目前为止仅在Linux上使用Chrome和FF进行了测试.


Ren*_*ger 9

这是另一个版本,基于@ 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;
  }
}
Run Code Online (Sandbox Code Playgroud)


Flo*_*Flo 7

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

<div #topicTitle contenteditable="true" [textContent]="model" (input)="model=topicTitle.innerText"></div>
Run Code Online (Sandbox Code Playgroud)

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

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