angular 2变量undefined

时间:2016-05-01 09:59:00

标签: variables angular undefined

我在angular2项目中有这段代码:

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

现在,问题在于:

当我点击或输入可编辑区域时,我在控制台中看到selrng值,因此它们已被设置,但是,它们似乎只对{{{{{ 1}}函数范围导致当我尝试插入表时,我将ngAfterViewInitsel都定义为未定义。有人能帮助我弄清楚我做错了什么吗?谢谢。

1 个答案:

答案 0 :(得分:1)

你需要在你的keyup和mouseup回调中使用箭头功能

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

另见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this