wolf3D
wolf3D

Reputation: 97

How do you run some code after an element is added to ngFor in Angular 2+?

I have a function in my component that adds an element to an array which is displayed by *ngFor in the view.

I wish to target the added element by an id and scroll to it after adding it to the array. Problem is this code runs before the element is added to the view.

How would I workaround this in Angular 2+?

Upvotes: 1

Views: 377

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657721

You can use a custom directive that does the notification:

@Directive({ selector: '[afterAdd]')
class MyDirective {
  @Output() added:EventEmitter = new EventEmitter();
  ngAfterContentInit() {
    this.added.next(null);
  }
} 

and use it like:

<div *ngFor="let item of items" afterAdd (added)="doSomething(item)">

this way doSomething() on the parent component will be called for each item added by *ngFor (also for the initial add of all items in the array)

alternatively you can also ensure the item was added to the DOM like

constructor(private cdRef:ChangeDetectorRef) {}

...
this.items.push(newItem);
this.cdRef.detectChanges(); // sync
// here the item was added to the DOM already

Upvotes: 2

Related Questions