What are the performance implications of using an object literal in the template when passing context to ng-template?
<ng-container *ngTemplateOutlet="template;context:{ field: value };"></ng-container>
as opposed to:
<ng-container *ngTemplateOutlet="template;context:context;"></ng-container>
context = { field: value }
Is change detection going to run more often in the first case, since it's (presumably) creating a new object?
/**
* We need to re-create existing embedded view if:
* - templateRef has changed
* - context has changes
*
* We mark context object as changed when the corresponding object
* shape changes (new properties are added or existing properties are removed).
* In other words we consider context with the same properties as "the same" even
* if object reference changes (see https://github.com/angular/angular/issues/13407).
*/
private _shouldRecreateView(changes: SimpleChanges): boolean {
const ctxChange = changes['ngTemplateOutletContext'];
return !!changes['ngTemplateOutlet'] || (ctxChange && this._hasContextShapeChanged(ctxChange));
}
Judging by this I would say it does make a difference because the function call is more expensive if "ngTemplateOutletContext"
is in changes
. And it always would be there if it's defined as an object literal in the template. This assumes that a new object is created every cycle. Is this assumption wrong?
I stumbled against this article explaining that a literal object in templates doesn't imply a new instance on every detect cycle. I checked it out with a modern versions of Angular and its behavior is the same. So, I suppose that construction like in your code snippet is okay and it can be used without any problem.