如何获得angular 2中子组件的大小?

如何获得angular 2中子组件的大小?,angular,Angular,我想把一个模态放在中心。它包含其他组件,因此位置取决于内容。我正试图以这种方式解决问题,但这不起作用,也不确定如何解决: 组件HTML: <div #modal [style.top]="positionTop" [style.left]="positionLeft"> <app-modal-one *ngIf="feature==='one'"> </app-modal-one> <app-modal-two *ngIf="feat

我想把一个模态放在中心。它包含其他组件,因此位置取决于内容。我正试图以这种方式解决问题,但这不起作用,也不确定如何解决:

组件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>
控制台日志显示大小为0。
如果我在显示后检查它,它会显示正确的大小。何时以及如何在全部显示之前/之后获取此大小(模式的大小)?

尝试
ngAfterViewInit
而不是
ngOnInit
我得到异常:如果我使用AfterViewInit或afterviewchecked,则检查后表达式已更改。请参见。使用
ngAfterViewInit
adn
ngAfterViewInit
this.cdRef.detectChanges()
添加到构造函数(私有cdRef:ChangeDetectorRef){}
中,并作为
ngAfterViewInit
中的最后一行!谢谢,应该是:
ngAfterViewInit
而不是您的评论中的
ngOnInit
。我是否可以在组件声明中使用reference变量,如@vishnu?我不完全理解这个问题。你想用
#ref1
做什么?我想要它的偏移高度。@毗瑟奴你可以用
'ref1'
代替我的例子中的
'modal'
,但我不知道这是否真的是你的意思,因为它看起来太明显了。
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){}

@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)   
}