使用execCommand在Angular中进行格式化

时间:2017-05-31 17:38:05

标签: angular typescript wysiwyg

我有这段代码:

  @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中传递给指令,以便它知道该特定按钮应该作用于什么。

1 个答案:

答案 0 :(得分:1)

我想你data对象上有document

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

另一方面,你使用的是data函数,我从未听说过。不在MouseEvent上,也不在HTMLElementDocument上。我的猜测是你试图访问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);
    }
}