Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 fire event after ngFor

Tags:

I'm trying to use a jQuery plugin which replaces the default scrollbar inside some dynamic elements in Angular 2.

These elements are created using an ngFor loop, that is I cannot attach the jQuery events to the elements these are created.

The application, at some point, mutates an Observable object which iscycled inside the ngFor in order to render the view.

Now, I would like to know when Angular finishes to draw my elements so that I can run the jQuery plugin.

  • I don't want to include any javascript in the HTML template.
  • I don't want to use the ngAfterViewInit, because this hooks is fired too many times
  • I don't want to implement a setTimeout-based solution (I think it's not reliable)

I found a solution by using the following custom Pipe: at the end of the ngFor cycle in the template, I write:

{{i | FireStoreEventPipe:'EVENT_TO_BE_FIRED'}}

Where FireStoreEventPipe is something like:

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

But this solution does not satisfy me.

Any suggestion for a better way?

Thanks

like image 433
Andrea Ialenti Avatar asked Apr 07 '16 16:04

Andrea Ialenti


1 Answers

I had a similar problem. I am using angular2 rc 1.

I solved it by creating a new component(a directive didnt work for me).

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);
   }
}

Then i imported in my wanted component as child component in the directives:

directives: [LastDirective],

In html:

<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>

And of course implement modalMembersDone()

like image 145
Nik Tsekour Avatar answered Sep 28 '22 04:09

Nik Tsekour