angular.js - angular2多个相同组件使用问题
PHP中文网
PHP中文网 2017-05-15 17:09:44
0
3
925

在父组件里面引用多个相同的子组件就像这样:

效果是生成两个文件上传控件如下:

因为控件是使用input和label来模拟的,所以需要在上传控件变化时获取文件名并付给控件显示,控件会绑定相关的绑定变量,监听函数如下:

但是为什么我点击第二个控件的时候总是改变了第一个控件的值而第二个没反应?

更新
额不好意思,忘记贴子组件模板了:

问题出在模板上面,我用了label的for来对应input的ID,然而ID一开始被我写死了,所以后面怎么操作只是对应到第一个ID上面,把ID和for改成动态的就可以了~

PHP中文网
PHP中文网

认证0级讲师

reply all(3)
Peter_Zhu

Thank you for the invitation, the code given is too little. . .

The reasons I guess for the problem:
1. Label css problem. For example, the first label is too large and covers the second area, mistakenly thinking that the second one is clicked.

2. The scope of the file upload component is not isolated. Among them, this refers to the parent CTRL.

漂亮男人

When you click on the second control, you should still get the first control. I guess it is because you did not identify these two controls.
Solution:
In angular 2 we usually use @Viewchild or @Viewchildren to define component identifiers for component nesting.
@Viewchild is generally used for a single control
@Viewchildren is used for multiple control combinations, such as li

So in the template you can write like this:
<cy-page-fileUploadEle #upload1></cy-page-fileUploadEle>
<cy-page-fileUploadEle #upload2></cy-page-fileUploadEle>

Then define these two properties in class
@Viewchild("upload1") upload1: CyPageFileUPloadEle; (class name of the control)
@Viewchild("upload2") upload2: CyPageFileUPloadEle; (class name of the control)

When calling, you can write like this:
this.upload1.nativeElement....

仅有的幸福

If I write, I will directly set the transparency of input[type="file"] to 0, and then the size will just cover the things below, so that I don’t have to worry about the for attribute of the label - -

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template