3

I have created a component with an event, lets call it (onAction). Within the same parent component or page, it is used in two places (which are components themselves). The difference is one place is used within an ng-template, which is used in a modal (NgbModal from the angular - bootstrap4 library to be exact).

The one not within the ng-template works fine. However, when the event inside the ng-template is fired, it is as if it is not bound with onActionB and the event is caught by the other component.

Here is some generic code to be clear, lets call it component "comp" for simplicity sake and the two of parent components that uses it "parentA" and "parentB"

<parentA>
...
   <comp (onAction)="onActionA($event)"></comp>
...
</parentA>

<parentB>
...
   <ng-template #someModal>
     <comp (onAction)="onActionB($event)"></comp>
   </ng-template>
...
</parentB>

When #someModal is rendered, it is as if the (onAction) is bind with onActionA in parentA. It triggers onActionA($event) instead of onActionB($event). The strange thing is if I comment out the comp in parentA, then onActionB in parentB is triggered.

Joshua Ting
  • 103
  • 7

2 Answers2

1

I have finally found my own answer:

The reason was the following template code in my component:

<label for="file-uploader" >
  <i class="fas fa-paperclip"></i> Upload File
</label>
<input #fileUploaderInput id="file-uploader" type="file" />

The same id in the input linked with the label trigger the same file change event. The fix is generate a random id for each component instance so they are unique across the current view:

<label for="file-uploader-{{randomId}}" >
  <i class="fas fa-paperclip"></i> Upload File
</label>
<input #fileUploaderInput id="file-uploader-{{randomId}}" type="file" />
Joshua Ting
  • 103
  • 7
0

To investigate your issue I have created this StackBlitz

https://stackblitz.com/edit/angular-p89q3z?file=src%2Fapp%2Fapp.component.html

I do not see the issue you are describing as clicking on the content in the template triggers onActionB

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • This is odd... I could not reproduce the problem on StackBlitz as well.. Here is a closer representation of my problem but it does not exhibit what I am experiencing in actual codes... https://stackblitz.com/edit/angular-xyca5d – Joshua Ting Apr 29 '19 at 04:29