My goal is to dynamically add and remove product images when a user clicks the add or delete button on the screen. However, I am encountering an issue where the function is not being called when dynamically injecting HTML and binding the click event. Below is a simplified version of the code.
<div class="product_images">
<div class="imageHeading">
<p>
Images
</p>
</div>
<div class="kt-form__group">
<div class="row">
<div class="col-lg-2 imageLabel">Main Image</div>
<div class="col-lg-3 imageLabel">Choose Image</div>
<div class="col-lg-2 imageLabel">Image</div>
<div class="col-lg-2 imageLabel">Actions</div>
</div>
</div>
<div class="imagesContainer" [innerHtml]="containerToAdd | sanitizeHtml">
</div>
</div>
Ts file
// Angular
import { Component, OnInit, ElementRef, ViewChild, ChangeDetectionStrategy, OnDestroy, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// Material
import { SelectionModel, MatPaginator, MatSort, MatSnackBar, MatDialog, MatRadioButton } from '@angular/material';
import { ProductManagementService } from '../../../../../core/e-commerce/_services/product-management.service';
import { ToastrService } from 'ngx-toastr';
import { ViewEncapsulation } from '@angular/core';
@Component({
selector: 'kt-product-edit',
templateUrl: './product-edit.component.html',
styleUrls: ['./product-edit.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class ProductEditComponent implements OnInit {
previewUrl : any = "/assets/media/images/noimage.jpg";
containerToAdd : string = "";
constructor(
private products: ProductManagementService,
private router: Router,
private route: ActivatedRoute,
private toastr: ToastrService,
private cdr: ChangeDetectorRef,
private FB: FormBuilder,
) {
}
ngOnInit() {
this.addImage();
}
addImage(){
this.containerToAdd = `
"<div class="kt-form__group image-container container-1">
<div class="row">
<div class="col-lg-2"><input type="checkbox" /></div>
<div class="col-lg-3"><input type="file" accept="image/*" (change)="imagePreview($event)" /></div>
<div class="col-lg-2"><img [src]="previewUrl" class="prod_image" /></div>
<div class="col-lg-2">
<span class="deleteElement" (click)="deleteImage()">
Del
</span>
</div>
</div>
</div>"`;
}
deleteImage() {
console.log("deleteImage");
}
}
Unfortunately, when clicking the span with the deleteImage() click event, the function is not being called.