6

I'm trying to center a modal. It contains other components, so the position depends on the content. I'm trying to get it this way, which doesn't work and not sure how to fix it:

component HTML:

  <div #modal [style.top]="positionTop" [style.left]="positionLeft">
    <app-modal-one *ngIf="feature==='one'"> </app-modal-one>
    <app-modal-two *ngIf="feature==='two'"></app-modal-two>
    <app-modal-three *ngIf="feature==='three'"></app-modal-three>
  </div>

component ts:

@ViewChild('modal') private modalContent: ElementRef;
ngOnInit() {
    this.modalHeight = this.modalContent.nativeElement.offsetHeight;
    this.modalWidth = this.modalContent.nativeElement.offsetWidth;
    this.positionLeft = (window.innerWidth - this.modalWidth) / 2 + "px";
    this.positionTop = (window.innerHeight - this.modalHeight) / 2 + "px";
    console.log("on init: "+this.modalWidth)    
  }

The console log shows the size as 0. If I check it later once it's displayed, it shows the right size. When and how can I get this size (of the #modal) before/or just after it's all displayed?

Piater
  • 63
  • 1
  • 3
  • 1
    Try `ngAfterViewInit` instead of `ngOnInit` – Günter Zöchbauer Apr 26 '17 at 14:18
  • I get Exception: Expression has changed after it was checked if I use AfterViewInit or AfterViewChecked – Piater Apr 26 '17 at 14:22
  • I see. add `constructor(private cdRef:ChangeDetectorRef){}` and as last line in `ngAfterViewInit` `this.cdRef.detectChanges()` – Günter Zöchbauer Apr 26 '17 at 14:23
  • Using `ngAfterViewInit ` adn `this.cdRef.detectChanges()` worked! Thank you – Piater Apr 26 '17 at 14:34
  • Does this answer your question? [How to get element's width/height within directives and component?](https://stackoverflow.com/questions/39813269/how-to-get-elements-width-height-within-directives-and-component) – rofrol Jun 10 '22 at 11:45

1 Answers1

5
constructor(private cdRef:ChangeDetectorRef){}

@ViewChild('modal') private modalContent: ElementRef;
ngAfterViewInit() {
    this.modalHeight = this.modalContent.nativeElement.offsetHeight;
    this.modalWidth = this.modalContent.nativeElement.offsetWidth;
    this.positionLeft = (window.innerWidth - this.modalWidth) / 2 + "px";
    this.positionTop = (window.innerHeight - this.modalHeight) / 2 + "px";
    console.log("on init: "+this.modalWidth)   
}
Cameron Gilbert
  • 884
  • 8
  • 23
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567