【问题标题】:How to read data attribute value in angular 6如何读取角度 6 中的数据属性值
【发布时间】:2018-10-08 15:18:33
【问题描述】:

我有文件控制,我正在使用 jquery 设置数据属性。但是当我提交表单时,我得到了数据属性的空值。

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代码

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

ad.ts

preview(event) {     
    console.log(event.target.getAttribute('data-filedata'))
}

【问题讨论】:

  • 使用 Angular 的 jquery 可能会混淆问题
  • Angular 和 JQuery 不能很好地混合。您应该尝试将其设为 100% Angular 解决方案。
  • 但是如何.......?
  • 其实很多其他的东西也是基于上面的jquery代码
  • 你为什么要混合使用 Angular 和 jquery?这是您尝试移植到 Angular 的旧 jquery 项目吗?还是从头开始?

标签: angular angular6


【解决方案1】:

你可能不应该混合使用 jquery 和 Angular,所以这里有一个没有 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'))
    }
}

由于 Angular 的更改检测周期,在您再次更改文件之前,您不会看到新值。但是,如果您使用浏览器的开发工具,您会看到 data-filedata 在您上传文件后立即更新。

Here's a stackblitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2019-08-28
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多