从 JavaScript 打开 ng2-bootstrap-modal dialogservice

Open ng2-bootstrap-modal dialogservice from JavaScript

我有一个这样的 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"
        });
    }
}

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

Cannot read property 'testPopup' of undefined.

有什么方法可以从 JavaScript 代码中调用 Angular2 组件函数吗?或者我生成树视图的方法不是那么多 Angular 方式吗?

this function 中的值未指向您的 class 实例,您应该改用箭头函数:

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

尝试 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
                }
}