0

I have file control and I am setting data attribute using jquery. But when I submit the form the I am getting null value of data attribute.

ad.html

<div class="field" align="left">
    <span>
        <h3>Upload your images</h3>
        <input type="file" id="files" data-filedata="" name="files[]"  multiple (change)="preview($event)" />
    </span>
</div>

Jquery code to set data attribute

$("#files").on("change", function(e) {      
    e.target.setAttribute('data-filedata', 'abc');
})

ad.ts

preview(event) {     
    console.log(event.target.getAttribute('data-filedata'))
}
6
  • 2
    using jquery with angular probably confuses the matter Oct 8, 2018 at 15:20
  • 1
    Angular and JQuery don't mix well. You should try to make this a 100% Angular solution. Oct 8, 2018 at 15:26
  • but how.......?
    – user10469417
    Oct 8, 2018 at 15:30
  • actually many other things are also based on the above jquery code
    – user10469417
    Oct 8, 2018 at 15:39
  • Why are you trying to mix Angular and jquery? Is this an old jquery project that you're trying to port to Angular? Or are you starting from scratch? Oct 8, 2018 at 15:42

1 Answer 1

6

You should probably not mix jquery and Angular, so here's a solution without jquery:

ad.html:

<div class="field" align="left">
    <span>
        <h3>Upload your images</h3>
        <input type="file" id="files" [attr.data-filedata]="filedata" name="files[]"  multiple (change)="preview($event)" />
    </span>
</div>

ad.ts:

class Ad {
   filedata = '';

    preview(event) {
        this.filedata = 'abc';
        console.log(event.target.getAttribute('data-filedata'))
    }
}

Because of the Angular's change detection cycle, you won't see the new value until you change the file a second time. But if you use your browser's dev tools you'll see that data-filedata is updated just after you upload a file.

Here's a stackblitz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy