Reputation: 7427
So, I am writing a bunch of filter components for a grid (Ag-Grid). I am going to display these filters in multiple locations, so I am writing a wrapper for them in order to access their value from different locations. Currently I'm implementing a filter drawer that will display the filters and am using an attribute directive app-drawer-item
to get a reference to them:
<app-filter-drawer #drawer [gridRef]="agGrid">
<app-text-filter app-drawer-item forColumn="AlertSid"></app-text-filter>
<app-date-filter app-drawer-item forColumn="Name"></app-text-filter>
</app-filter-drawer>
As you can see, there will be a number of filters, so it wouldn't be prudent to hard code them into app-filter-drawer
. I am using @ContentChildren
from app-filter-drawer
to get a reference to the directives on each of them.
Is it possible to get a reference to a property of a filter component (like app-text-filter
) from the app-drawer-item
directive? I have been messing around with ElementRef
and ViewContainer
but I don't see a way to reference the component instance directly. I am able to get it via event binding to the host, but I only need to access the values when the user clicks an 'Apply' button and it seems wasteful to emit an event each time the value is updated. There are also other methods in the component that I'll eventually need to invoke from the directive.
I can provide more info if needed. Thanks!
Upvotes: 4
Views: 698
Reputation: 7427
I found a relatively easy solution to this. You can just use the Injector
in the directive to manually inject the closest found token from the injector tree, which should be the parent:
export class DrawerItemDirective {
constructor(@Inject(FilterDrawerComponent) public drawer) {}
ngAfterViewInit() {
const prop = this.drawer.propertyIWantToAccess;
this.doStuff(prop);
}
}
Upvotes: 2