Aniruddh Thakor
Aniruddh Thakor

Reputation: 1616

How to add click event in dynamic HTML in ionic 4?

I have added one item using JQuery but i want to add click event to remove this item but click is not triggered,So please help me.

This is my code,

.ts file

addmore() {
    var html = "<ion-item class='Ids" + this.exp + "' style='margin: 15px 10px 0px 10px;'>";
    html += " <ion-label position='floating' style='color: gray !important;'>Experience</ion-label>";
    html += " <ion-input type='text'></ion-input>";
    html += " <ion-icon class='remove' name='remove-circle' slot='end' style='margin-top:12%;font-size:18px;' (click)='removeExp()'></ion-icon>";
    html += "</ion-item>";
    console.log(this.exp);
    $(".experience").append(html);
    this.exp++;
  }

removeExp() {
    console.log("hi");
  }

Upvotes: 0

Views: 3085

Answers (2)

Hardik
Hardik

Reputation: 3258

Please have a look on this stackblitz url.

// necessary changes for component.
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      public exp = 2;
  experiences: any = [];
  constructor(public navCtrl: NavController) {
    this.experiences = [{ expId: 1, value: '', lable: '' }, { expId: 2, value: '', lable: '' }]
  }
    }

    // necessary changes for html code
    <div class="experience">
        <ion-item class="Ids" *ngFor="let ex of experiences">
            <ion-label position="floating">Experience {{ ex.expId }}</ion-label>
            <ion-input type="text"></ion-input>
            <!-- <ion-icon name="close-circle"></ion-icon> -->
        </ion-item>
  </div>
  <ion-item style="--border-style: none;">
    <ion-label slot="end" style="text-align: right; text-decoration: underline;" (click)="addmore()">Add more
    </ion-label>
    <ion-label slot="end" style="text-align: right; text-decoration: underline;" (click)="remove()">Remove
    </ion-label>
  </ion-item>

For more info please visit this url

Working Url https://stackblitz.com/edit/ionic-qh4ucv

Url with Javascript: https://stackblitz.com/edit/ionic-58drvj You might face other issue if you use javascript or jquery.

Note: ion-icon not working with stack blitz directly. So, I put prompt there for get index of item to remove

Upvotes: 1

Ravindra Patel
Ravindra Patel

Reputation: 337

try following code

function addClickEvent() {
  $(document).on('click', 'your-selector', function () {
      var btn = $(this);
      // do anything
  });
}

// Shorthand for $( document ).ready()
$(function () {
    addClickEvent();
});

Upvotes: 0

Related Questions