【问题标题】:Angular 2: Get reference to component property from attribute directiveAngular 2:从属性指令获取对组件属性的引用
【发布时间】:2023-04-06 02:45:01
【问题描述】:

所以,我正在为网格(Ag-Grid)编写一堆过滤器组件。我将在多个位置显示这些过滤器,因此我正在为它们编写一个包装器,以便从不同位置访问它们的值。目前我正在实现一个过滤器抽屉,它将显示过滤器并使用属性指令app-drawer-item 来获取对它们的引用:

<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>

如您所见,会有许多过滤器,因此将它们硬编码到app-filter-drawer 中是不明智的。我正在使用来自app-filter-drawer@ContentChildren 来获取对它们每个指令的引用。

是否可以从app-drawer-item 指令中获取对过滤器组件属性(如app-text-filter)的引用?我一直在搞乱ElementRefViewContainer,但我看不到直接引用组件实例的方法。我可以通过与主机的事件绑定来获取它,但是我只需要在用户单击“应用”按钮时访问这些值,并且每次更新值时发出一个事件似乎很浪费。我最终需要从指令中调用组件中的其他方法。

如果需要,我可以提供更多信息。谢谢!

【问题讨论】:

    标签: angular typescript angular2-directives


    【解决方案1】:

    我找到了一个相对简单的解决方案。您可以在指令中使用Injector 手动注入从注入器树中找到的最近的令牌,它应该是父级:

    export class DrawerItemDirective {
    
        constructor(@Inject(FilterDrawerComponent) public drawer) {}
    
        ngAfterViewInit() {
            const prop = this.drawer.propertyIWantToAccess;
            this.doStuff(prop);
        }
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多