Bibek Gautam
Bibek Gautam

Reputation: 592

Open ng2-bootstrap-modal dialogservice from JavaScript

I have an Angular component like this:

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

I am trying to open ng2-bootstrap-modal popup in callback method onNodeSelected treeview, but testPopup() function cannot be called and it displays:

Cannot read property 'testPopup' of undefined.

Is there any way to call an Angular2 component function from JavaScript code? Or isn't my approach to generate treeview so much Angular way?

Upvotes: 0

Views: 404

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29715

Try fat arrow => syntax instead of using 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();
            }
    }

Alternatively you can store a this object in some variable and try it.

var self = this;

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

Upvotes: 1

kemsky
kemsky

Reputation: 15271

this value in function is not pointing to your class instance, you should use arrow function instead:

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

Upvotes: 1

Related Questions