0

I am having trouble referencing a child component in a larger project so I dropped these into the project just for my own sanity check.

In any instance @ViewChild AND @ViewChildren ALWAYS return undefined. What I need is to get the position and dimensions of a child element...

What can I do to try and resolve this?

Components are exported through a module...

Used in view like this

<app-parent>
    <app-child></app-child>
</app-parent>

Child:

@Component({
  selector: 'app-child',
  template: `<div>Stuff</div>`,
  })
export class ChildComponent {
  constructor() { }
}

Parent:

@Component({
  selector: 'app-parent',
  template: `<div><ng-content></ng-content></div>`,
})
export class ParentComponent implements OnInit, AfterViewInit {

  @ViewChild(ChildComponent) child: any;
  @ViewChildren('app-child') childrenMethod: QueryList<ElementRef>;

  constructor() { }
  ngOnInit(): void {
    console.log(this.child); // returns undefined
  }
  ngAfterViewInit() {
    console.log(this.child);  // returns undefined
    this.childrenMethod.changes.subscribe(item => {
      console.log('??' + this.childrenMethod); // nothing happens
  });
}

Is there a different approach to getting the child element so I can work with it's position and dimensions?

GRowing
  • 4,629
  • 13
  • 52
  • 75
  • 2
    When using `ng-content` you need to use `ContentChild` instead of `ViewChild` – J. Pichardo May 25 '18 at 17:35
  • 1
    What J. Pichardo says: https://stackblitz.com/edit/angular-4vzmax – Marcel Hoekstra May 25 '18 at 17:46
  • I just wanna cry now,, lol. Thank you! One issue though. If I declare @ContentChild(ChildComponent) child: ElementRef; .. this this.child.nativeElement.offsetHeight ... throws an error unhandled error TypeError: Cannot read property 'offsetHeight' of undefined – GRowing May 25 '18 at 17:56

0 Answers0