首页 > 解决方案 > 从组件外部关注组件内部的输入

问题描述

场景如下,我有一个上传文件的组件,但它看起来真的很难看(经典input type="file"),所以我想制作一个风格化的标签(可能是图像或其他东西),当你点击它时,你会得到相同的行为,好像您单击了文件输入。

我设法通过在upload.component我想要使用的模板中使用我的模板来完成这项工作,但由于我需要在许多不同的地方上传文件,我不想每次都重复代码。

这工作得很好..

.image-upload > input
{
    display: none;
}
<div class="image-upload">
    <label for="file-input">
        <img src="placeholder.jpg"/>
    </label>

    <input id="file-input" type="file"/>
</div>

这不..

<!-- my-other.component.html -->
<label for="file-input">
    <img src="placeholder.jpg"/>
</label>
<app-upload></app-upload>

<!-- upload.component.html -->
<input id="file-input" type="file" />

那么有没有办法引用组件内“封闭”的输入?

标签: htmlcssangularangular-components

解决方案


有同样的问题,我所做的是

CSS:

#file{
    position: absolute; 
    top: -100vh;
}

HTML:

<input type="file" id="file" name="file">
<a onclick="select_file()" id="file_button">File</a>

jQuery JS:

function select_file(){
    $('#file').click();
}

我认为您可以使用 vanilla JS 来做到这一点,但我已经在我的项目中包含了 jQuery,所以无论如何......并且带有 onclick 的元素不必是链接


推荐阅读