[Angular] Some performance tips

The talk from here.

1. The lifecycle in Angular component:

constructor vs ngOnInit:

Constructor: only used for injection.

ngOnInit: for data initlization.

About ngOnInit: 

I am not sure the example is good or not. Because it is not a good choice to use 'document.querySelector'.

this.elDuceDateContainer = document.querySelector('.dueDatePopover-container')

I would rather use 'ref' or '@ViewChild'. But might be it is a good adivse that avoid init too many variable in ngOnInit if not going to use right away.


You have to know that why change detection works. It handle async code and setTimeout, setTimeInterval, DOM event, mouse event... they are all async opreations.

So it will trigger change detection. 

If you have to use setTimeout in your component, and you don't want change detection to detect the changes, you can use NgZone to make it run outside the change detection.

constructor(private ngZone: NgZone) {}

ngAfterViewInit() {
  this.ngZone.runOutsideAngular(() => this.paint());
} 

Noramlly I won't use any jQuery plugin. But take this as an advise.

原文地址:https://www.cnblogs.com/Answer1215/p/6471365.html