我试图以模态为中心。它包含其他组件,因此位置取决于内容。我试图以这种方式获取它,这不起作用,也不确定如何解决它:
组件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>
组件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)
}
控制台日志显示大小为0。 如果我稍后检查它,它会显示正确的大小。何时以及如何在#Ital之前或之后获得此尺寸(#modal)?
答案 0 :(得分:3)
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)
constructor(private cdRef:ChangeDetectorRef){}
}