В angular2 образом, я буду создавать пользовательские директивы, чтобы получить высоту и ширину любого элемента. Для img
я применим его (директиву) в теге img
, и всякий раз, когда я хочу получить высоту & ширину img, мне просто нужно щелкнуть по нему. вы можете изменить в соответствии с вашими потребностями.
DEMO: https://plnkr.co/edit/3tibSEJCF734KQ3PBNZc?p=preview
directive.ts
import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';
@Directive({
selector:"[getHeightWidth]",
host:{
'(click)':"show()"
}
})
export class GetEleDirective{
constructor(private el:ElementRef){
}
show(){
console.log(this.el.nativeElement);
console.log('height---' + this.el.nativeElement.offsetHeight);
console.log('width---' + this.el.nativeElement.offsetWidth);
}
}
app.ts
@Component({
selector: 'my-app',
template: `
<div style="width:200px;height:300px">
<img getHeightWidth <!-- here I'm using getHeightWidth directive-->
[src]="source" alt="Angular2"
width="100%"
height="100%">
</div>
`,
})
export class AppComponent {
source='images/angular.png';
}
Вы должны получить сам объект изображения, а затем попросить размеров. Как выглядит ваш код? – John