0

I am trying to clone the button, while I am able to clone the button, but for some reason the cloned button does not have the click function.

app.component.html:

<div class="container">
    <div class="row">
        <div class="col-md-6">
            <input type="button" (click)="CloneButton($event)" value="Clone">
        </div>
        <div class="col-md-6" #cloned></div>
    </div>
</div>

app.component.ts:

@ViewChild('cloned') cloned:ElementRef;
cloneCounter = 0;

CloneButton(event:any) {
    let newbutton = event.target.cloneNode();
    newbutton.value += this.cloneCounter++;
    this.cloned.nativeElement.appendChild(newbutton);
}

Even when I attach the javascript event listener in CloneButton(), it would then be unable to access the cloneCounter variable

newbutton.addEventListener('click', this.jsclicked,false)

jsclicked() {
    console.log('jsclicked');
    console.log(this.cloneCounter); //will be undefined.
}

How do I clone the button, so that it still have the working click function?

j4rey
  • 2,582
  • 20
  • 34
  • You could use a delegated event listener so it is bound automatically to any cloned items: https://stackoverflow.com/questions/25248286/native-js-equivalent-to-jquery-delegation – Pete Jan 08 '18 at 11:37
  • if i use addEventListener, the delegated function is unable to access the component variables e.g., `cloneCounter`. – j4rey Jan 08 '18 at 11:43

0 Answers0