繁体   English   中英

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

[英]Angular 2: how to get directive attributes using 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> 

lightbox.directive.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>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM