【问题标题】:Using execCommand in Angular 2 application在 Angular 2 应用程序中使用 execCommand
【发布时间】:2017-06-01 22:31:22
【问题描述】:

我正在尝试创建一个所见即所得的编辑器,我已经完成了:

export class WysiwygEditorComponent extends OnInit {
  editor:any;
  ngOnInit() {
    this.editor = document.getElementById('editor')
  }
  iBold() {
    this.editor.execCommand('bold', false, null);
  }
}

这是它的 HTML:

<div>
  <input type="button" (click)="iBold()" value="B">
</div>
<div id='editor' contenteditable>
  <h1>A WYSIWYG Editor.</h1>
  <p>Try making some changes here. Add your own text.</p>
</div>

这是我的错误:

TypeError: Cannot read property 'document' of undefined
    at WysiwygEditorComponent.iBold

如何获取 html 元素以便我可以调用 execCommand,以便它可以根据调用的函数进行更改?

【问题讨论】:

  • 我对@9​​87654325@不太熟悉,但根据我有限的研究,它似乎是document上的一种方法,而不是HTML元素
  • WysiwygEditorComponent 的选择器是什么?
  • @snorkpete - 非常感谢。我犯了较早的错误并且没有返回使用文档,但只是一个更改修复了它。如果您将您的评论作为答案,我会接受。
  • 如果您有答案,请将其作为答案发布,而不是作为问题的一部分。

标签: javascript angular typescript wysiwyg


【解决方案1】:

问题在于execCommand 不是 html 对象的一部分,而是文档对象的一部分,因此错误指的是 HTML 元素。文档必须首先在designMode 中,然后才能公开此功能。

所以,这就是问题所在:

this.editor.execCommand('bold', false, null);

改为

document.execCommand('bold', false, null);

这解决了问题。

有关更多信息,尤其是所有可能的命令,请查看MDN 页面。

【讨论】:

  • 虽然这段代码 sn-p 可以解决问题,including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • 我的意思是,我知道这是你自己的问题,但是为了后代看着它... ;-) 现在看起来好多了!赞成。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-17
  • 2017-03-20
  • 2016-06-25
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多