Angular: Get ViewChildren inside of directive

210 Views Asked by At

I have a component called SomeComponent. This component contains some Elements like a paragraph which has a template reference variable attached to it. Here is an example of SomeComponent


@Component({
  selector: "some-component",
  template: ` <p #isValid>Hello from Component</p> `
})
export class SomeComponent {
}

I use SomeComponent in my AppComponent. Now I want to have a Directive attached to SomeComponent that gets all Elements of SomeComponent that have the #isValid template reference variable.

My approach was using ViewChildren inside of the Directive for this. Here is an example of the directive.

@Directive({ selector: "[getIsValid]" })
export class GetIsValidDirective implements AfterViewInit{
  @ViewChildren("isValid") isValidChildren: QueryList<unknown>;

  ngAfterViewInit() {
    console.log("isValidChildren defined?", this.isValidChildren);

    this.isValidChildren?.changes.subscribe((next) =>
      console.log("isValidChildren changes", next)
    );
  }
}

SomeComponent and GetIsValidDirective are used in the AppComponent like this:

@Component({
  selector: "app-root",
  template: ` <some-component getIsValid></some-component> `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {}

I expected to get all Elements that hasl isValid attached to it inside the GetIsValidDirective. But this.isValidChildren is always undefined.

Am I missing something obvious here or is this just not possible because the directive has no access to the inner view of SomeComponent?

0

There are 0 best solutions below