如何定位'this'组件html属性elementRef.nativeElement.querySelector('。content-img')?
有没有比做nativeElement.querySelector更好的方法?
我有一个组件和一个输入。
从输入中我定位 imgChange()的组件功能 在imgChange()中,我想定位组件元素''和 get .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;
}
}
答案 0 :(得分:2)
使用ViewChild。在你的情况下你应该喜欢
@Component({
template: `
<ng-content></ng-content>
<div #contentImg class="content-img"></div>
})
并在您的类中使用ViewChild注释声明一个局部变量
@ViewChild('contentImg') contentImg;