角度

2017-05-31 2 views
1

にフォーマットするためのexecCommandを使用して、私はこのコードを持っている:角度

@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); 
    }); 

しかし、これは動作しませんが。 execCommandが機能していることを確認したいので、最初のif文はスキップされます。

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で、id:editorのdivに渡すべきであると感じているので、その特定のボタンが何をするべきかを知っています。

答えて

1

あなたのdocumentオブジェクトにdataがあるとします。

とにかく$eventHostListenerに渡しています。これにより、HTMLElementの代わりにtargetElementMouseEventになります。このようなエラーを予知するためにタイプヒントを使用することができます。

一方、私が聞いたことのない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); 
    } 
} 
+0

ありがとうございます。これは私の出発点でした:https://codepen.io/Shokeen/pen/pgryyN –