How can I reattach a click event to cloned elements in Angular2?

I've implemented a table list with the use of *ngFor. Each list item includes a hidden details div and a button to show the details. Following the list items, outside of the table div, there is an empty div. Upon clicking the show details button for each table item, the details div is retrieved and added as inner HTML to the empty div, then animated. However, I've encountered an issue where the click event for the button inside the cloned details div is not firing.

<li *ngFor="let item of items">
   <div id="item-div">
    .......
    .......
    <button (click)="showDetails($event, item._id)">Show Details</button>
   </div>

   <!--  Item details (hide)  -->
   <div id="item-details" class="item-details-info">
     .........
     .........
     .........
     <button (click)="saveItem(item._id)">Save Item</button>

   </div>

</li>

<!-- Custom popup like div, but its not a popup, its an animated div -->
<div id="custom-animated-div" class="custom-popup">
   <div class="popup-data"></div>
   <div class="popup-close" (click)="closePopup();">
      <i class="material-icons">&#xE5CD;</i>
   </div>
</div>

Below is the component code responsible for cloning and animating:

showDetails (event: any, itemId: string) {
   var target = event.target || event.srcElement || event.currentTarget;
  this.togglePopup(target, itemId);
}

togglePopup(element: any, itemId: string) {
   this.popup = document.querySelector('.custom-popup');
   if (this.popup.classList.contains('active')) {
   this.closePopup();
   setTimeout(this.togglePopup, 600);
}
else {
  setTimeout(() => {
    document.querySelector('.custom-popup').classList.add('active');
    this.cloneInfo(element, itemId);
  }, 100);
  // this.popup.addClass('active');
 }
}


cloneInfo(element: any, jobId: string) {
  var parentElement = $(element).parents('.item-row').find('.item-details-info');
  var self = this;
  setTimeout(() => {
    document.querySelector('.custom-popup').children.item(0).innerHTML = parentElement.html();
    document.querySelector('.custom-popup').children.item(0).classList.add('fadeInUp');

  }, 100);
}

Despite my attempts to add the event inside the clone function using addEventListener, the button event inside the cloned animated div is still not functioning properly.

Answer №1

Although I am unable to provide a comment at this time, it is recommended to utilize ViewContainerRef and TemplateRef in place of innerHTML, as well as bindings instead of classList.add. By following these suggestions, everything should function correctly.

Answer №2

To display detailed information, use interpolation with double curly braces {{}}.

In a TypeScript file, you can create a new item and implement the showDetails($event, item) function as shown below:

showDetails(item: Item) {
    this.newitem = item;
    // Perform additional actions here
}

In your HTML file:

<div *ngIf="newitem" id="custom-animated-div" class="custom-popup">
   <div class="popup-data"> 
       {{newitem._id}} 
        <br> 
        {{newitem.name}} </div>
        <div class="popup-close" (click)="closePopup();">
        <i class="material-icons">&#xE5CD;</i>
   </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protected members in Angular 2 component templates using TypeScript

Reflecting on ways to incorporate members in a component that can be accessed from the template but not from a parent component sparked my curiosity. In exploring TypeScript visibility in Angular 2, I encountered discussions about "public" and "private" d ...

The error message "Property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'." appeared while using the IONIC Moodle App

Having an issue in the IONIC Moodle App with a typescript error stating that property 'hideKeyboardAccessoryBar' does not exist on type 'Keyboard'. An ionic error occurred when running CMD, displaying the following error: [14:58:02] ...

Error message displaying 'class-transformer returning undefined'

I'm new to working with the class-transformer library. I have a simple Product class and JSON string set up to load a Product object. However, I'm encountering an issue where even though I can see the output indicating that the transformation was ...

`The utilization of a collective interface/data type within an Angular application`

I created a HeaderComponent that requires an object with the structure of {title: string, short_desc: string} as its input property. @Component({ selector: 'header', templateUrl: './header.component.html', styleUrls: ['./hea ...

Is it feasible to have two interfaces in Typescript that reference each other?

I am facing an issue with two interfaces, UserProfile and Interest. Here is the code for both interfaces: export default interface UserProfile { userProfileId: string, rep: number, pfpUrl: string, bio: string, experience: "beginner" | " ...

Utilize the CSS class or variable within an Angular TypeScript file for enhanced styling and functionality

Is it possible to utilize the scss class or variable in a typescript file? scss .thisIsGreen { color: green; } .thisIsBlue { color: blue; } Alternatively, you can use $thisIsGreen { color: green; } $thisIsBlue { color: blue; } Now, I want to ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Establish a connection between a React variable and state management

In my codebase, I have an external module file named Task.ts. It contains the following: const taskList: Task[] = []; Class Task { ... } export { Task, taskList } The taskList is a list of Task objects that can be modified by the Task class. Now, i ...

The error "commands.reduce is not a function" is encountered when using the router.navigate function in

When I try to send a string as a link to my router, such as "/blog/pages/3", I encounter the error "commands.reduce is not a function". Surprisingly, despite the error message showing up in the console, the navigation still works. goToPage(link) { this ...

What could be the reason for my npm package installed globally to not be able to utilize ts-node?

Recently, I've been working on developing a CLI tool for my personal use. This tool essentially parses the standard output generated by hcitool, which provides information about nearby bluetooth devices. If you're interested in checking out the ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Angular ngFor not displaying the list

I'm encountering an issue with my HTML page where I'm using NGFor with an array. The error message I receive is as follows: landingpage.component.html:142 ERROR Error: Cannot find a differ supporting object '[object Object]' of type &ap ...

Combining types: unable to utilize the second optional type within a for loop

I am facing an issue while looping through an array due to the union type. I am wondering what I have overlooked in the code below that is causing Visual Studio Code to not recognize the second optional type for that specific array. class Menu { // name ...

Strategies for splitting a component's general properties and accurately typing the outcomes

I am attempting to break down a custom type into its individual components: type CustomType<T extends React.ElementType> = React.ComponentPropsWithoutRef<T> & { aBunchOfProps: string; } The code appears as follows: const partitionProps = ...

Utilizing Dependency Injection in RouteReuseStrategy

I have been utilizing a custom RouteReuseStrategy and found invaluable resources like this answer to help me understand the process. However, I am facing a dilemma: My strategy relies on one of my services to determine if the user has logged out, in which ...

Building a .NET Core 3.1 application that integrates SQL Server 2019 Express for managing multiple databases, including a main database dedicated to

I'm currently developing a web application using .NET Core 3.1 and Angular 9. I am curious to know if it is feasible to leverage the internal authentication/authorization system in .NET Core to connect to an "authorization" database. This would allow ...

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

Implementing a Dynamic Component within ngx-datatable's row-detail feature

I'm currently working on a project where I need to implement a reusable datatable using ngx-datatable. One of the requirements is to have dynamic components rendered inside the row details. The way it's set up is that the parent module passes a c ...

Angular 2 Checkbox Filtering: Simplifying Your Data Selection

Presented are a series of tasks in the form of objects within a table, accompanied by two checkboxes: "Night" and "Day". The desired scenario involves filtering the tasks based on the checkbox selections. If the "Night" checkbox is checked, only tasks wit ...

Struggling with the incorporation of Typescript Augmentation into my customized MUI theme

I'm struggling with my custom theme that has additional key/values causing TS errors when I try to use the design tokens in my app. I know I need to use module augmentation to resolve this issue, but I'm confused about where to implement it and h ...