Can I use vanilla javascript in Ionic?


#1

so in my web app, I used something like this

var id1 = '';

var imgPreview1 = document.getElementById('img-prev1');
var fileUpload1 = document.getElementById('file-input1');

fileUpload1.addEventListener('change', function (event) {
    var file = event.target.files[0];
    var formData = new FormData();
    formData.append('file', file);
    formData.append('upload_preset', CLOUDINARY_UPLOAD_PRESET);

    axios({
        url: CLOUDINARY_URL,
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: formData
    }).then(function (res) {
        console.log(res);
        imgPreview1.src = res.data.secure_url;
        id1 = res.data.secure_url;
        console.log(id1);
    }).catch(function (err) {
        console.log(err);
    });
});

in Ionic, can I use something like this? like bind this piece of javascript to an <input type="file">?


#2

Assuming that you are talking about the current version of Ionic, yes you could do this (an Ionic application does just use Javascript in the end, so you can use whatever kind of Javascript you like), but it would be much better to use the norms/conventions available through Ionic/Angular since everything you are doing could be swapped out with the Angular equivalent.

If you are more interested in just using the Ionic UI components with your existing application, then it would probably be a better idea to use the Ionic 4 web components as they don’t require the use of Angular (and it wouldn’t make a whole lot of sense using the code you have above in an Angular environment).


#3

Yeah but Ionic web component doesn’t have input type='file'. I tried doing a workaround where I created a js file and imported it. So far, the console.log tests have worked (trying to capture the event where there’s a change in the file uploaded).

Can you perhaps give me a link where it’s similar to my case and they use Ionic web components instead? :slight_smile:


#4

See: iOS 11 its not me its you (tags: iOS11, PWA, Camera)