Angular2 Do Actions After Dom Has Finished Rendering

Angular2 do actions after dom has finished rendering

AFAIK you just have ngAfterViewChecked and ngAfterViewInit for detecting dom updates.

In my experience, sometimes you need to write the code for dom changes inside a settimeout to schedule a macrotask (asynchronous update) for that so that your code will run in the next cycle of change detection (which is exactly what you need). For more details see this article

Place your could inside a settimeout in the end of your block code (and remove it from ngAfterViewChecked).
Some examples:

setTimeout(() => htmlInputElement.focus()); // focus an input
setTimeout(() => htmlElement.scrollIntoView()); // scroll into view

Execute a method when DOM finishes rendering the elements

I think you can solve this using lifecycle hooks of Angular. You can go through the documentation of angular lifecycle hooks and use it as per your need.

Update dom after component rendered the view, best practice in Angular2?

How about adding a custom directive to each of your "seat" elements and let that directive add the CSS class?

In your template, the directive would be used as follows (I'm guessing, since you didn't show your template):

<div *ngFor="let seat of seats" [highlight]="seat.id">
...
</div>

You need to pass some information to the directive to identify which seat it is working on. It seems better to pass an id directly (e.g. seat.id) rather than to rely on HTML ids (although in your case they might be one and the same).

Now the code for the directive:

@Directive({
selector: '[highlight]'
})
export class HighlightDirective {
@Input() highlight: string; // This will contain a seat.id

constructor(el: ElementRef, ss: SeatService) {
const selectedSeats = ss.getSelectedSeats();
// If current seat found in selectedSeats, mark it as selected.
if (selectedSeats.indexOf(this.highlight) !== -1) {
this.el.nativeElement.classList.add('selected');
}
}
}

The reason I'm using an external service SeatService to get the data from localStorage is that Angular will create an instance of HighlightDirective for every match it finds in your template. You don't want to refetch the selected seats in every instance (the service lets you cache the seats and return the same data).

Angular 2 execute script after template render

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and its children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks



Related Topics



Leave a reply



Submit