0

I have been bangin my head on the wall for 2 days now, just to attach a click event to a dynamically created button. (click), ng-click, on-click directives won't work on dynamic doms, as these directives need to be compiled.

I have this requirement to create dynamic html elements (button is one), but somehow i am stuck on how to attach the event. Calling the ts method on onClick will not work either.

I have looked here and there, but to no avail. If someone could shed a light, it is much appreciated.

I am looking into switching to other framework as i find angular lacking event binding to dynamic doms. I'm already tired and exhausted looking for anything that will do, but none.

Please help.

Jeff
  • 760
  • 1
  • 12
  • 26
  • Did you try this : https://stackoverflow.com/questions/42692780/how-to-add-click-event-to-dynamically-added-html-element-in-typescript – willmaz Jun 26 '18 at 14:41
  • Better https://stackoverflow.com/questions/35080387/dynamically-add-event-listener-in-angular-2 – Eliseo Jun 26 '18 at 14:46
  • Hi guys, thanks for your suggestions, bookmarked those links for future use on complex implementations. – Jeff Jun 27 '18 at 04:07

1 Answers1

0

I solved my own issue using either ngFor/ngRepeat. The trick was to declare the ngModel variable first for use on the dynamic doms, best if made array.

In my case, i needed an iterating key-value pairs that is dynamically generated via add new tag button. Here's the code snippet.

<div *ngFor="let tag of resourceTags; index as i" [attr.data-index]="i">
                        <div class="col-sm-5"><input type="text" class="form-control" required="" [(ngModel)]="tag.key" value="{{tag.key}}" placeholder="tag key" /></div>
                        <div class="col-sm-5"><input type="text" class="form-control" required="" [(ngModel)]="tag.value" value="{{tag.value}}" placeholder="tag value" /></div>
                        <div class="col-sm-2" style="padding-top:7px;"><i class="fa fa-minus-circle fa-lg" style="cursor:pointer;" (click)="removeTag(i)"></i></div>
                        <div class="col-sm-12" style="height:5px;">&nbsp;</div>
                    </div>
                    <div class="col-sm-2"><button type="button" class="center btn btn-info btn-xs" (click)="addNewTag()">add new tag</button></div>
                    <div class="col-sm-10">&nbsp;</div>

Where resouceTags is defined as an array variable of [{'key':'some key', 'value':'some value'}, ...]

Angular will automatically render the specified ngFor elements as soon as the variable changes contents.

addNewTag() will just add an element to resourceTags, and removeTag does the opposite.

I was stupid not to have thought about this one earlier.

Jeff
  • 760
  • 1
  • 12
  • 26