5

Calling a Method in the Component from a Javascript - Angular2

 3 years ago
source link: https://www.codesd.com/item/calling-a-method-in-the-component-from-a-javascript-angular2.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Calling a Method in the Component from a Javascript - Angular2

advertisements

I need to call a method declared in my Angular component from a Javascript I have written inside the constructor of the same component. My target is to detect the change of a file input filed and upload the file to the server through a service.

I have added this declaration after the imports.

declare var $: any;

In my constructor, I have written following code.

$(document.body).on("change.bs.fileinput", ".fileinput-exists", function () {

    console.log($(this).parent().find('.myImage').val());
    let input = $(this).parent().find('.myImage');
    this._photoToBeSaved = input.prop('files')[0];
    console.log("my file = " + this._photoToBeSaved);
    //upload the image
    () => {
        this.uploadPhoto(this._photoToBeSaved);
    }
});

Following is the uploadPhoto method in the same component.

uploadPhoto(photo: any) {
    console.log("here i am at upload method);
    // call service method to upload
    .....
}

However, this does not work.

Note that for the following part in the constructor, I have followed the answer for this question. Can I really do that. Is it correct?

() => {
   this.uploadPhoto(this._photoToBeSaved);
}

the uploadPhoto() method does not get called. Why is that? How to correct this?


Found the solution. Posting it here, so that it might help someone in need.

I do not know the reason why the way I have asked in the question does not call the method in Angular2 component. The way to go for is ARROW FUNCTIONS.

$(document.body).on("change.bs.fileinput", ".fileinput-exists", (event: Event) => {
    alert("fired");
    let photoToSave = $(event.currentTarget).parent().find('.myImage').val();
    this.uploadPhoto(photoToSave);
});

the uploadPhoto() method gets called fine now.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK