2017-12-05 6 views
1

구성 요소의 너비를 가져 오려고하지만 0입니다. 또한 ngOnChanges()에 코드를 넣으려고했습니다.각도로 절대 위치 요소의 너비를 얻는 방법

constructor(private element: ElementRef) { 
    this.htmlElement = this.element.nativeElement; 
    let width = this.htmlElement.offsetWidth; 
} 

요소 스타일 :

display: block; 
position: absolute; 
left: 100; 

내가 clientWidth를 사용하여 시도()하지만 너무 0입니다. 각도 2에있는 요소의 너비는 어떻게 알 수 있습니까?

업데이트 :

나는 절대 위치를 사용하지 않는 폭이 올바른지, 그래서 나는 절대 위치 지정된 요소의 폭을 얻는 방법 질문은 가정?

+0

코드를 추가 하시겠습니까? – Aravind

+0

디스플레이 블록이있는 div 만 해당 –

답변

1

시도를 AfterViewInit 라이프 사이클 후크 방식으로 코드를 이동하고,에 직접 요소를 삽입하는 대신 @ViewChild() 데코레이터를 사용하십시오..

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

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div #child> 
     <h2>Hello!</h2> 
    </div> 
    `, 
}) 
export class App implements AfterViewInit { 
    @ViewChild('child') element: any; 
    htmlElement: HTMLElement; 

    constructor() {} 

    ngAfterViewInit() { 
    this.htmlElement = this.element.nativeElement; 
    let width = this.element.nativeElement.offsetWidth; 
    } 
} 

또는 참조 the working example here :

이 코드를 사용해보십시오. 또한 설명에 대한 설명을 확인하십시오.

+0

동일한 결과가 여전히 0 –

+0

문제는 요소에 대한 참조를 얻는 방법에있는 것처럼 보입니다. 당신이'constructor'에 요소를 주입 할 때 그것은 DOM에서 아직 렌더링되지 않습니다. 그리고 당신은 수동 변경 탐지를하지 않기 때문에 디폴트 값인'0'을 유지합니다. 대신 [@ViewChild()] (https://angular.io/api/core/ViewChild) 데코레이터로 요소를 참조하십시오. [작업 예제] (https://plnkr.co/edit/0GIA0r0w5e7TP2DBhd1n)를보고 도움이되는지 알려 주시면 답변을 업데이트 할 수 있습니다. –

+0

질문이 업데이트 되었습니까? –

0

에 한번 사용 :

const rect = this.element.nativeElement.getBoundingClientRect(); 
const width = rect.width; 
+0

너비가 여전히 0이면 –

0

당신은하여 elementRef에 요소에 연결해야

@ViewChild('foo') foo: TemplateRef; 

<div #foo> 
    <h2>Hello {{name}}</h2> 
</div> 
    {{foo.clientWidth}} 

LIVE DEMO

관련 문제