Ricardo Castañeda
Ricardo Castañeda

Reputation: 5812

Ionic add a click function to dynamically created div

From my code I have a function that can create div elements multiple times (with surroundContents()), how can I make these created div elements to trigger a function inside the class of the very same page?

More precisely, I need that any of these div elements (created with function createDiv()) be able to trigger with click the function called clickCreatedDiv(arg) located in MyPage class and pass any string as an argument. I have tried this element.setAttribute('(click)', 'clickCreatedDiv()'); but with no success. How can I achieve this behavior?

export class MyProvider {
  wrapSelection(comment) {
    let element = document.createElement("div")
    element.setAttribute('(click)', 'clickCreatedDiv()');
    element.surroundContents(element);
  }
}

import { MyProvider } from '../../providers/my-provider';
@Component({
    selector: 'page-mypage',
    templateUrl: 'mypage.html',
}) 
export class MyPage {
  constructor(public myprovider: MyProvider) {}
  createDiv() {
    this.myprovider.wrapSelection();
  }

  clickCreatedDiv(arg) { // This is what I want to trigger with click
    alert('click ' + arg);
  }
}

Upvotes: 1

Views: 3066

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The Angular event binding syntax (click)="doSomething()" cannot be used to set the event handler on a dynamically created HTML element. To make it work, you can pass the event handler from the MyPage class, and set it with element.addEventListener:

export class MyProvider {
  wrapSelection(eventHandler) {
    let element = document.createElement("div")
    element.addEventListener("click", () => { eventHandler("Some text"); });
    ...
  }
}

In MyPage, the event handler should be defined as an arrow function to preserve this and allow to access the class members:

createDiv() {
  this.myProvider.wrapSelection(this.clickCreatedDiv);
}

clickCreatedDiv = (arg) => {
  alert('Clicked: ' + arg);
}

See this stackblitz for a demo.

Upvotes: 1

AndrWeisR
AndrWeisR

Reputation: 1226

I would pass the click function as a callback to wrapSelection. E.g. something like:

export class MyProvider {
  wrapSelection(comment, onClick) {
    let element = document.createElement("div")
    element.setAttribute('(click)', onClick);
    element.surroundContents(element);
  }
}

export class MyPage {
  constructor(public myprovider: MyProvider) {}
  createDiv() {
    this.myprovider.wrapSelection('Some comment', this.clickCreatedDiv);
  }

  clickCreatedDiv(arg) { // This is what I want to trigger with click
    alert('click ' + arg);
  }
}

Upvotes: 1

Related Questions