Reputation: 5
I have this piece of code in my angular2 project:
import {bootstrap} from 'angular2/platform/browser';
import {Component, AfterViewInit} from 'angular2/core';
import {DROPDOWN_DIRECTIVES} from 'ng2-bootstrap/ng2-bootstrap';
@Component({
selector: '<aInsertTable></aInsertTable>',
templateUrl: './app/templates/insertTable/insertTable.html',
directives: [DROPDOWN_DIRECTIVES],
})
export class InsertTableComponent implements AfterViewInit {
public status:{isopen:boolean} = {isopen: false};
public sel: any;
public rng: any;
ngAfterViewInit(){
jQuery('#editable-area').keyup(function(){
this.sel = window.getSelection();
this.rng = this.sel.getRangeAt(0);
})
jQuery('#editable-area').mouseup(function(){
this.sel = window.getSelection();
this.rng = this.sel.getRangeAt(0);
console.log(this.sel);
console.log(this.rng);
})
}
public toggleDropdown($event:MouseEvent):void {
this.status.isopen = !this.status.isopen;
}
insertTable(x, y) {
console.log(this.sel);
console.log(this.rng);
if (!$tableId) {
var $tableId = 0;
}
var table = document.createElement("Table");
table.id = "table" + $tableId;
table.className = "dynamic-table table";
$tableId++;
for (var i = 0; i < y + 1; i++) {
var tr = document.createElement('tr');
for (var j = 0; j < x + 1; j++) {
var td = document.createElement('td');
tr.appendChild(td);
};
table.appendChild(tr);
};
this.rng.insertNode(table);
}
}
Now, here's the problem:
when I click or type in the editable area, I see the sel
and rng
values in my console, so they are being set, but, they seem to be available only to the ngAfterViewInit
function scope cause when I try inserting a table I get both sel
and rng
as undefined. Can someone help me figuring out what I'm doing wrong? Thank you.
Upvotes: 0
Views: 716
Reputation: 214345
You need to use arrow function in your keyup and mouseup callbacks like this
jQuery('#editable-area').keyup(() => {
this.sel = window.getSelection();
this.rng = this.sel.getRangeAt(0);
})
jQuery('#editable-area').mouseup(() => {
this.sel = window.getSelection();
this.rng = this.sel.getRangeAt(0);
console.log(this.sel);
console.log(this.rng);
})
Upvotes: 1