Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2.

These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them.

At some point, the application updates an Observable object which is cycled through in the ngFor for rendering purposes.

Now, I am seeking a way to determine when Angular has finished rendering my elements so that I can execute the jQuery plugin.

  • I prefer not to include any JavaScript in the HTML template.
  • Using ngAfterViewInit is not ideal as it fires too frequently.
  • I do not want to resort to a setTimeout-based solution as I find it unreliable.

I came across a potential solution involving a custom Pipe: at the end of the template's ngFor cycle, I add:

{{i | FireStoreEventPipe:'EVENT_TO_BE_FIRED'}}

The FireStoreEventPipe would look something like this:

transform(obj: any, args:any[]) {
    var event = args[0];
    //Fire event
    return null;
}

However, I am not entirely satisfied with this solution.

Any recommendations for a more effective approach?

Thank you

Answer №1

I encountered a similar issue that I needed to address. Currently, I am utilizing angular2 rc 1.

To resolve it, I opted to develop a new component as creating a directive was not effective in my case.

import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
   selector: 'islast',
   template: '<span></span>'
})
export class LastDirective {
   @Input() isLast: boolean;
   @Output() onLastDone: EventEmitter<boolean> = new EventEmitter<boolean>();
   ngOnInit() {
      if (this.isLast)
        this.onLastDone.emit(true);
   }
}

Subsequently, I included the newly created component as a child component in the directives of my desired component:

directives: [LastDirective],

In the HTML code:

<tr *ngFor="let sm of filteredMembers; let last = last; let i=index;" data-id="{{sm.Id}}">
     <td>
        <islast [isLast]="last" (onLastDone)="modalMembersDone()"></islast>
     </td>
 </tr>

Lastly, make sure to implement the modalMembersDone() function as well.

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

What could be causing the malfunction of my button's event handlers?

Users can fill out a form in which they provide information about a grocery item they want to add to their cart. After completing the form, they can click on the "Add Item" button. Here's the form in my app.component.html: <form (ngSubmit)="a ...

Error: The component passed is invalid and cannot be defined within kendo UI

Check out this example https://www.telerik.com/kendo-vue-ui/components/grid/ showcasing a computed method gridSearchMessage() { return provideLocalizationService(this).toLanguageString( "gridSearch", "Search in all colu ...

Implement a loading bar on the entire page in Vue.js while a request is being made

There is an "edit" button on my page which allows me to edit certain elements and either save or close without saving. I would like to implement a loading bar that displays when the user clicks the "save" button, indicating that the data is being processe ...

Nested Add and Remove using Jquery

I'm looking for assistance with implementing add/remove functionality for both top-level and sublists, which should result in a serialized output. Can anyone provide guidance on how to achieve this? For example: Add Question Question 1 | Delete An ...

The use of Buffer() is no longer recommended due to concerns regarding both security vulnerabilities and

I'm encountering an issue while trying to run a Discord bot. The code I'm using involves Buffer and it keeps generating errors specifically with this code snippet: const app = express(); app.get("/", (req,res) => { if((new Buffer(req.quer ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...

Efficiently linking styles through computation in Angular

So I've been working with Angular5 and I figured out how to bind an HTML element's style to a Boolean value. However, I'm struggling to find a way to do this for multiple styles simultaneously. For example, I have this code snippet that wor ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

ngx-bootstrap encountered an issue: TypeError - _co.openModal is unavailable as a function

Just starting out with ngx-bootstrap, I was attempting to create a modal using the instructions from this site : However, I encountered the following error: ERROR TypeError: _co.openModal is not a function Here are some code snippets: //app.component ...

How to set focus on the active accordion in jQuery accordion?

**Update: I've cracked the code! ** This is how I achieved it: $("#accordion").accordion({ header:'h3', active: '#section1', autoheight: false, clearstyle: true, }).bind("change.ui-accordion", func ...

Converting objects to arrays in Typescript: A step-by-step guide

Can anyone assist me in converting a string to a Typescript array? Any help would be greatly appreciated. Take a look at the following code snippet: private validateEmptyOption(): any { console.log("CHECKED") let isValid = true; this.currentF ...

What steps can be taken to enable JSONIX to handle additional XML elements during the deserialization process?

JSONIX 2.0.12 is truly impressive. I am working with a substantial XML file and I am only looking to convert certain elements into JSON format. Whenever I omit some elements from my mapping file, JSONIX throws an unexpected element error during deseriali ...

Having trouble getting the submit function to work in the Primeng p-dialog form

I am struggling to perform a file upload using the primeng p-dialog component. The issue I am facing is that the Submit button does not seem to be working at all, and there are no error messages being displayed in the console. Despite extensive research on ...

What is the best way to navigate a link in Angular (15) that requires multiple parameters to be input?

I came across the following link: "https://api.api-soccer.com/v1/championship/10/stages/168" My goal is to access the data within the ID /168, but I first need to access the ID at /10. Unfortunately, I'm unsure of how to achieve this using Angular. ...

Issue with Vue.js: document.querySelector is returning a null value even though the element clearly exists

I'm currently working on implementing a responsive navbar following Kevin Powell's tutorial, but I've run into an issue. For some reason, when I try to select the element with the class 'primary-navigation' using 'const primar ...

Setting up the CHROME_BIN path in Jenkins environment variable for running Headless Chrome without Puppeteer can be achieved by following these

Currently, I am facing an issue in my Angular project where I can successfully run tests using Karma and Jasmin on my Windows local machine with headless chrome. However, Jenkins is giving me an error stating "No binary for ChromeHeadless browser on your p ...

The client.postMessage() function in a service worker is not being recognized by the onmessage handler within an AngularJS controller

Handling Service Worker Messages: let angularClient; self.addEventListener('message', function(event) { // store the client that sent the message in the angularClient variable angularClient = event.ports[0]; }); Service Worker Notificat ...

Data in the array is only updated upon refreshing the webpage

Why is the array empty when I navigate to a new route (/category/name-of-category) that renders my Category component, but it gets data when I refresh the page? What am I missing here? To better explain, I have created a video. Video showcasing the issue: ...

Steps to resolve the issue of 'type is not assignable to any' while working with a member

I'm facing an issue with a code snippet like the one below: interface IFoo { bar: string; baz: number; } function f(foo: IFoo, name: 'bar' | 'baz', val: any) { foo[name] = val; // <<< error: Type 'any' i ...

How to Modify a Module that was Imported in Typescript

Apologies for my inexperience in this language. I've been working on a custom Discord bot and encountered a problem. I implemented the feature to load commands dynamically from a folder, with each command as a module. However, when trying to create a ...