Angular 2:如何使用nativeElement获取指令属性



我需要访问lightbox.directive.ts中的指令属性。我想使用 nativeElement,因为我需要使用 .getBoundingClientRect(( 获取元素的坐标。在一个指令中,我想访问其余指令的实例。因此,在示例中,我将指向 #images 的链接作为参数 [lightboxImages] = "images" 传递。

谢谢。

app.component.html

<div #images>
<img *ngFor="let image of myImages" 
[src]="image.path" 
lightbox
[lightboxImages]="images"
[fullImagePath]="image.fullImagePath" />
</div> 

灯箱指令.ts

export class LightboxDirective {
index; // any image index
@Input() images; 
@Input() fullImagePath;  
get thumbnailImage(){
return this.images.getElementsByTagName("img")[this.index];
}
get thumbnailImagePosition(){
return this.thumbnailImage.getBoundingClientRect();
}
get thumbnailImageFullPath(){
return this.thumbnailImage['attributes']['fullImagePath']; // ? 
}
}

您可以将ElementRef注入到指令中,它是对添加指令的元素的引用。

然后,您可以访问本机元素:

constructor(elementRef: ElementRef) {
this.nativeElement = this.elementRef.nativeElement;
}

您可以考虑创建另一个"容器"指令,该指令注入所有LightboxDirective并管理它们。您可以在"容器"指令中注入所有特定类型的指令:

@ContentChildren(LightboxDirective, { descendants: true })
lightboxes: QueryList<LightboxDirective>;

最新更新