Shamshad Jamal
Shamshad Jamal

Reputation: 19

Event Binding in angular4

I want to call methods on click event bind click event on ngOnInit() using angular4. My requirement is to bind click event on span which i have done it but when i call my other method using if conditions then gives me the error this.getSellingChats is not a function in console. here is my code

ngOnInit() { 

this.scrollToBottom();
this.getallChats();
this.checkConnection();
setTimeout(() => {
    this.bindClickevents();    
}, 3000);

}

bindClickevents(){
$('tabset ul li a').find('span').bind('click',function(event){

    var _tab = $(this).text();
    if(_tab == 'ALL'){
        this.getallChats();
    }
    else if(_tab == 'SELLING'){
        this.getSellingChats();

    }
    else if(_tab == 'BUYING'){
        this.getBuyingChats();
    }
    else if(_tab == 'BLOCKED'){
        this.getBlockedChats();
    }
});

}

Basically what i want to achieve is bind click event on span and then user click on different tabs methods called according to if conditions. I don't want to call the following methods in ngOnInit() method.

    this.getSellingChats();
    this.getBuyingChats();
    this.getBlockedChats();

Please provide me solution. Will be highly appreciated.

Upvotes: 0

Views: 197

Answers (1)

Yousef khan
Yousef khan

Reputation: 3194

this is not the reference of your component inside the find method. Try it like following.

    bindClickevents(){
    const comp = this;
    $('tabset ul li a').find('span').bind('click',function(event){

        var _tab = $(this).text();
        if(_tab == 'ALL'){
            comp.getallChats();
        }
        else if(_tab == 'SELLING'){
            comp.getSellingChats();

        }
        else if(_tab == 'BUYING'){
            this.getBuyingChats();
        }
        else if(_tab == 'BLOCKED'){
            comp.getBlockedChats();
        }
    });
    }

Upvotes: 2

Related Questions