I have this code:
@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);
});
But this isn't working. The first if
statement will be skipped as I just want to ensure that the execCommand
is working.
It does print out the console.log
so it gets into that function.
The HTML element that will be modified is:
<div id='editor' contenteditable>
<h1>A WYSIWYG Editor.</h1>
<p>Change this text, or format</p>
</div>
How do I change the text that was selected, for bold? How do I use document.execCommand in Typescript?
I have a feeling in this section, document.execCommand(targetElement
that I should have passed in the div with id editor
to the directive so it know what that particular button should act upon.
I suppose you have data
on your document
object.
Anyways, you are passing in the $event
into the HostListener
. This will make the targetElement
a MouseEvent
instead of a HTMLElement
. You can use type hinting to foresee such errors.
On the other hand you are using a data
function, from which I've never heard of. Not onMouseEvent
nor on a HTMLElement
or Document
. My guess is that you are trying to access the dataset
? If that's the case, this might work for you:
@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);
}
}