【问题标题】:Angular2 Form works in Index.html but does not work in component.htmlAngular2 Form 在 Index.html 中有效,但在 component.html 中无效
【发布时间】:2016-11-13 09:17:50
【问题描述】:

为什么这个上传文件表单示例在Index.html 中有效,而在任何component.html 文件中都无效?

如果我将它移动到任何 component.html 单击添加文件甚至不会打开浏览对话框。

  <form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
        <div id="drop">
                <a>Add File</a> Drag and Drop
                <input type="file" name="upl" />
        </div>

        <ul id="uploadList"></ul>
  </form>

编辑:我必须提一下,我只在Index.html 中导入js 文件,我也没有在System.jsangular-cli.build.js 中导入

在 Index.html 中的引用之一是:

<script src="assets/js/uploadScript.js"></script>

这是来自uploadScript.js 的代码,应该会打开浏览器对话框:

$('#drop a').click(function(){
    $(this).parent().find('input').click();
});

【问题讨论】:

  • 我更惊讶的是,Add File 链接对您有用,会打开对话框。您确定吗?对我来说,它适用于组件和 index.html,但我必须点击输入..在 Chrome 和 IE 中测试
  • 是的,它在 Index.html 中工作。我从一个旧项目中导入了文件并尝试实现 angular2 组件。看看我的编辑。也许这就是原因?
  • 好吧,那么在您的 javascript 文件中,必须有某个地方可以处理“添加文件”链接并使其工作..在第一个答案stackoverflow.com/questions/10216331/… 中类似这里的东西尝试找到该代码并在这里发布
  • 再次编辑。我发布了我认为打开对话框的代码。但是,如果它是在 Index.html 中导入的,那是否会自动在所有 Angular2 组件中使用而无需在 system.js 中导入它们?

标签: html angular


【解决方案1】:

您在uploadScript.js 中的代码(我猜)是在DOM 准备好时初始化的,这就是JQuery 初始化的基本工作方式。但是由于你的组件还没有在 DOM 中,所以什么也找不到。

您需要将初始化代码直接放入您的组件中,以便在正确的时间调用它,当表单实际在 DOM 中呈现时。

尝试像这样改变你的组件:

import { Component, ElementRef } from '@angular/core';

// reference to jQuery
declare var $: any;

@Component({
    selector: 'my-component',
    template: `

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
    <div id="drop">
        <a (click)="addFile()">Add File</a> Drag and Drop
        <input type="file" name="upl" />
    </div>

    <ul id="uploadList"></ul>
</form>

`
})
export class JQueryComponent
{
    // get the ElementRef
    constructor(private _elRef: ElementRef)
    {
    }

    public addFile(): void
    {
        $(this._elRef.nativeElement).find('#drop a').parent().find('input').click();
    }
}

重要的部分是使用 Angular 2 (click) 直接绑定到 Add File 锚点。 ElementRef 提供对您的 html DOM 元素的引用,可用于模拟 input type="file"

上的实际点击事件

【讨论】:

  • 或者这里是另一个没有jQuery使用@ViewChild的解决方案,你也可以检查一下stackoverflow.com/questions/36639486/…
  • 谢谢。这会触发浏览事件,但恐怕这只是冰山一角!为了使整个上传工作正常工作,它使用了更多库,例如:jquery.knob.js, jquery.ui.widget.js, jquery.iframe-transport.js, query.fileupload.js, initializer.js and a upload.php,我的直觉告诉我,我应该忘记整个事情并寻找一个 angular2 上传按钮(我做了但无法进行任何工作)...... . . ,除非你认为有一种简单的方法可以让它们以某种方式工作?
  • 如果你忘记了整个事情并在 Angular 2 中完成,它肯定会帮助你将来了解 angular2 的工作原理等等。但是正如我所说,如果你不想重写整个逻辑上,只要确保,此刻,你初始化你的 jQuery 代码,你已经准备好你的 DOM 指令......这可以发挥整个魔力。查找组件的 ngAfterViewInit() - 这是复制和粘贴整个 jquery 上传文件逻辑的地方
  • 谢谢,但我暂时放弃 jquery。我接受了你的回答,因为在这条路上再往前走毫无意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-26
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 2015-07-21
  • 2015-08-03
相关资源
最近更新 更多