2017-06-11 38 views
1

如何定位'this'組件html屬性elementRef.nativeElement.querySelector('。content-img')?如何定位這個組件的HTML屬性,有沒有更簡單的方法來獲取這個元素?

有沒有比nativeElement.querySelector更好的方法?

我有一個組件和一個輸入。

從輸入我定位的分量函數是imgChange() 在imgChange()我想靶向組分元素''得到.offsetWidth

app.ts

<image-component #Img format="png"></image-component> 
<input (change)="Img.imgChange($event)" type="file"> 

圖像component.ts

@Component({ 
    template: ` 
     <ng-content></ng-content> 
     <div class="content-img"></div> 

}) 
export class ResizingCroppingImagesComponent{ 
    public elementRef; 
    public _format = 'jpeg'; 
    public img = null; 
    public sizeW = 230; 
    public sizeH = 150; 
    public sizeWmax = 720; 
    public sizeHmax = 720; 
    public stateMouse = false; 
    public stateType = 'none'; 
    public stateR = 'none'; 
    public centerX = 0; 
    public centerY = 0; 
    public percent = 100; 
    public imgUrl = null; 
    public _top = 0; 
    public _left = 0; 
    public _img = {}; 
    public _src = null; 

    public imgDataUrl; 
    public origImg; 
    public imgWidth; 
    public imgHeight; 

imgChange(event) { 

    const _this = this; 
    const fileReader = new FileReader(); 
    fileReader.onload = ev => { } 

    _this._left = (_this.elementRef.nativeElement.querySelector('.content-img').offsetWidth/2) - _this.imgWidth/2; 

} 

} 

回答

2

使用ViewChild。在您的情況建議立即進行刪除不喜歡

@Component({ 
    template: ` 
     <ng-content></ng-content> 
     <div #contentImg class="content-img"></div> 

}) 

並在類中聲明與ViewChild註釋的局部變量,

@ViewChild('contentImg') contentImg; 
相關問題