从JavaScript打开ng2-bootstrap-modal对话服务

时间:2017-11-03 09:36:18

标签: jquery angular typescript ng2-bootstrap

我有一个像这样的Angular组件:

export class TestComponent implements OnInit {
    @Input() TestData: TestObject[];
    constructor(private dialogService: DialogService) { }

    ngOnInit() {
        this.RenderTreeView();
        $('#treeviewStandard').treeview('collapseAll', { silent: true });
    }

    RenderTreeView() {
        $('#treeviewStandard').treeview({
            data: this.TestData,         
            onNodeSelected: function(event, data) {
                console.log(data);
                if (data.isOverlaid) {
                    //testPopup isnt opening ng2-bootstrap-modal since this is angular 2 function 
                    //and dialogService is unknown to javascript 
                    this.testPopup();
                }
            }
        });        
    }

    testPopup() {       
        this.dialogService.addDialog(PopupComponent, {
            majorObject: this.TestData,
            moduleType:"check"
        });
    }
}

我正在尝试在回调方法ng2-bootstrap-modal树视图中打开onNodeSelected弹出窗口,但无法调用testPopup()函数并显示:

  

无法读取未定义的属性'testPopup'。

有没有办法从JavaScript代码调用Angular2组件函数?或者不是我的方法来生成树视图这么多 Angular 方式?

2 个答案:

答案 0 :(得分:1)

this中的

function值未指向您的类实例,您应该使用箭头函数:

RenderTreeView() {
    $('#treeviewStandard').treeview({
        data: this.TestData,         
        onNodeSelected: (event, data) => {
            console.log(data);
            if(data.isOverlaid)
                {
                    //testPopup isnt opening ng2-bootstrap-modal since this is angular 2 function 
                    //and dialogService is unknown to javascript 
                    this.testPopup();
                }
          }
    });        
}

答案 1 :(得分:1)

尝试使用fat arrow =>语法,而不是使用function

onNodeSelected: (event, data) =>{

            console.log(data);
            if(data.isOverlaid)
            {
                    //testPopup isnt opening ng2-bootstrap-modal since this is angular 2 function 
                    //and dialogService is unknown to javascript 
                    this.testPopup();
            }
    }

或者,您可以将this对象存储在某个变量中并尝试使用。

var self = this;

onNodeSelected: function(event, data) {
                console.log(data);
                if(data.isOverlaid)
                 {
                        self.testPopup();  // called using variable
                }
}