【问题标题】:Using execCommand for formatting in Angular在 Angular 中使用 execCommand 进行格式化
【发布时间】:2017-05-31 17:38:05
【问题描述】:

我有这个代码:

  @HostListener('document:click', ['$event'])
  onClick(targetElement) {
    console.log(targetElement);
    var command = 'bold';
    if (command == 'h1' || command == 'h2' || command == 'p') {
      document.execCommand('formatBlock', false, command);
    } else document.execCommand(targetElement.data('command'), false, null);
  });

但这不起作用。第一个if 语句将被跳过,因为我只是想确保execCommand 正在工作。

它确实会打印出console.log,因此它会进入该函数。

要修改的HTML元素是:

<div id='editor' contenteditable>
  <h1>A WYSIWYG Editor.</h1>
  <p>Change this text, or format</p>
</div>

如何将所选文本更改为粗体? 如何在 Typescript 中使用 document.execCommand?

我在这部分有一种感觉,document.execCommand(targetElement,我应该将 ID 为 editor 的 div 传递给指令,以便它知道该特定按钮应该作用于什么。

【问题讨论】:

    标签: angular typescript wysiwyg


    【解决方案1】:

    我想你的document 对象上有data。

    无论如何,您正在将$event 传递给HostListener。这将使targetElement 成为MouseEvent 而不是HTMLElement。您可以使用类型提示来预见此类错误。

    另一方面,您正在使用data 函数,我从未听说过。不在MouseEvent 上,也不在HTMLElement 或Document 上。我的猜测是您正在尝试访问dataset?如果是这种情况,这可能对您有用:

    @HostListener('document:click', ['$event.target'])
      onClick(targetElement: Document) {
        let command: string = 'bold';
        if (command === 'h1' || command === 'h2' || command === 'p') {
           document.execCommand('formatBlock', false, command);
        } else {
           document.execCommand(targetElement.dataset['command'], false, null);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 2018-03-10
      相关资源
      最近更新 更多