Search code examples
angulardecoratorangular-directive

Access directives of child components using ViewChildren


For accessing the directives in a component, I have tried Angular 2: Get reference to a directive used in a component but this doesn't work for directives in the child components of the component.

The child components are created dynamically using ViewContainerRef.

 @ViewChildren(ViewRefDirective) allMyDirectives; 

//This doesn't work for directives in the child components

I have multiple different child components, that's why I can't specify the name of a single child component in ViewChild for accessing its directives.

Directive

@Directive({
  selector: '[view-ref-host]',
})
export class ViewRefDirective {
  constructor(public viewContainerRef: ViewContainerRef) {
   }
}

Parent component

<div>
  <div view-ref-host>Parent block
    <child-panel-one></child-panel-one>
    <child-panel-two></child-panel-two>
    <child-panel-three></child-panel-three>
  </div>
</div>

Child panel one component

<div>
  <div view-ref-host>Child panel one
    <!-- html here -->
  </div>
</div>

Child panel two component

<div>
  <div view-ref-host>Child panel two
    <!-- html here -->
  </div>
</div>

Child panel three component

<div>
  <div view-ref-host>Child panel three
    <!-- html here -->
  </div>
</div>

How can I use the ViewChild decorator to access all the directives in parent and child component?


Solution

  • You can define method in your parent component like:

    allMyDirectives: ViewRefDirective[] = [];
    
    registerRef(ref: ViewRefDirective) {
      this.allMyDirectives.push(ref);
    }
    

    and register directive in directive's constructor:

    @Directive({
      selector: '[view-ref-host]',
    })
    export class ViewRefDirective {
      constructor(
        public viewContainerRef: ViewContainerRef,
        @Optional() parent: AppComponent
      ) {
        if (parent) {
          parent.registerRef(this);
        }
      }
    } 
    

    Ng-run Example