Angular: custom decorator to override behavior of built-in ViewChild

183 Views Asked by At

I am trying to write a "shorthand" decorator/annotation to use instead of @ViewChild, by overriding its default behavior with {static: true} (I am migrating an Angular 4 app to 13, which has several TemplateRefs (mainly passed as column cell-templates into ngx-datatables, built using ngx-semantic).

Since I do not modify any other behaviors of @ViewChild, I tried the simple/dumb approach of:

import {ViewChild} from '@angular/core';

export function StaticChild(selector) {
  return ViewChild(selector, {static: true});
}

And using @StaticChild('selectorExpr') on the relevant component fields, instead of @ViewChild('selectorExpr', {static: true}).

This works, but not for all cases; it works if I annotate a field in one component and use/pass the reference within the same component, but if I access such a reference (through a getter) from another component and use it in the latter, it does not get propagated. (If I instead use the standard @ViewChild.. with static opt on one of these "indirectly" referenced fields, it starts getting propagated as expected; so I'm guessing it has something to do with the annotation metadata population/association.)

I would like to understand what I am missing/doing wrong with my StaticChild definition.

0

There are 0 best solutions below