1

I'm using my-component in the angular material custom CdkStepper. The custom CdkStepper works and renders the my component. But it looks like impossible to get the height and width of my-component when I use it in the custom CdkStepper. If the component is used outside the stepper, the height and width will be not 0.

import { AfterViewInit, Component, ElementRef } from '@angular/core';

@Component({
  selector: 'my-component',
  templateUrl: './image-editor.component.html',
  styleUrls: ['./image-editor.component.scss'],
  host: { 'class': 'd-block' }
})
export class MyComponent implements AfterViewInit {

  constructor(private el: ElementRef) {  }

  public ngAfterViewInit(): void {  
    console.log(`offsetWidth : ${(this.el.nativeElement as HTMLElement).offsetWidth}`); // offsetWidth : 0
  }
}
<lib-stepper linear (selectionChange)="selectionChangeData=$event">
    <cdk-step>
        <ng-container *ngIf="selectionChangeData?.selectedIndex === 0 || selectionChangeData?.selectedIndex == null ">
          
          <!-- works and will be displayed, but 'offsetWidth' is always 0  -->
          <my-component></my-component> 
        
        </ng-container>
    </cdk-step>
    ...
</lib-stepper>

Anyone know why the height and width is always 0?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Matthias
  • 15
  • 3
  • Does this answer your question? [Angular lifecycle hook after all children are initialized](https://stackoverflow.com/q/38763248/1264804)? – isherwood Aug 24 '22 at 12:57
  • FYI, you've confused backticks (`\``) and apostrophes (`'`) in your post. – isherwood Aug 24 '22 at 12:59

1 Answers1

0

Can you try an alternative method called getBoundingClientRect

import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  ElementRef,
} from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css'],
})
export class ChildComponent implements OnInit {
  @Input() message: string;
  @Output() informParent = new EventEmitter();

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {}

  ngAfterViewInit() {
    console.log(this.elementRef.nativeElement.getBoundingClientRect());
    // if the above doesn't work, wrap the above line in a setTimeout like so
    setTimeout(() => {
     console.log(this.elementRef.nativeElement.getBoundingClientRect());
    });
  }

  takeAction() {
    this.informParent.emit('The child triggered an event');
  }
}

forked stackblitz

Naren Murali
  • 19,250
  • 3
  • 27
  • 54