user10469417
user10469417

Reputation:

How to read data attribute value in angular 6

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'))
}

Upvotes: 1

Views: 14213

Answers (1)

ShamPooSham
ShamPooSham

Reputation: 2379

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

Upvotes: 7

Related Questions