Home > database >  How can I get ViewChildren of a Directive when it is inside an ngIf with async pipe
How can I get ViewChildren of a Directive when it is inside an ngIf with async pipe

Time:01-20

I have a component that renders its content based on an observable with async pipe.

<div *ngIf="equipment$ | async as equipment">
  <button myDirective></button>
</div>

In the .ts file, I'm getting all of the MyDirective children. There can be any number.

@ViewChildren(MyDirective) actions!: QueryList<MyDirective>;

And then I want to access it in the ngAfterViewInit.

ngAfterViewInit(): void {
  console.log(this.actions)
}

this logs a QueryList with 0 items. If I put the directive outside of my async pipe it all works perfectly:

<div *ngIf="equipment$ | async as equipment">
  // Some HTML here
</div>
<button myDirective></button>

Is there any way I can retrieve the directives nested under the async pipe? I need to keep the ngIf because I have inputs bound to the equipment variable (which contains properties).

CodePudding user response:

you need to add static: false since it's a dynamically rendered component:

@ViewChildren(MyDirective, { static: false }) actions!: QueryList<MyDirective>;

but you won't be sure that the directive will be available in ngAfterView init. because equipment$can take some time...

maybe you can add a tap() in the observable and do your console.log() there istead

CodePudding user response:

You can create a hide directive, let me expain it:

    @Input() hide: boolean;

constructor(private renderer: Renderer2, private elRef: ElementRef) {
}

ngOnChanges() {
    if (this.hide) {
        this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'hidden');
    } else {
        this.renderer.setStyle(this.elRef.nativeElement, 'visibility', 'visible');
    }
}

since the hide directive will not display the element on the dom but it can still be accesible

  •  Tags:  
  • Related