获取单击div的宽度,高度和偏移量 - Angular 2

时间:2017-03-01 21:51:24

标签: angular angular2-directives

我有一个模板,可以使用*ngFor创建一个链接列表,还有一个单独的div元素,我想根据当前活动的链接更改其位置。

模板:

<div #divHandle
    *ngFor="let link of links; let i = index"
    class="div-link"
    (click)="changeActiveLink(i)">
    <h2>{{link}}</h2>
</div>
<div
[@indexState]="activeLink"
id="highlighter"></div>

这导致了如下结构:

<div class="div-link">
  <div (click)="changeActiveLink(0)"><h2>Link 1</h2></div>
  <div (click)="changeActiveLink(1)"><h2>Link 2</h2></div>
  <div (click)="changeActiveLink(2)"><h2>Longer link 1</h2></div>
  <div (click)="changeActiveLink(3)"><h2>Longer link 2</h2></div>
</div>
<div id="highlighter"></div>

我希望我的荧光笔div在Link 1时获得activeLink = 0的宽度。与此简单的js相似:

var High = document.getElementById('highlighter');
High.style.width = document.getElementsByClass('div-link')[0].children[activeLink].offsetWidth; //activeLink = 0

在我的app.component.ts文件中:

import { Component, AfterViewInit, ViewChildren, Directive, QueryList, ElementRef} from '@angular/core';

@Directive({selector: '[class~=div-link]'})
@Directive({selector: '.div-link'}) // variant
@Directive({selector: '#divHandle'}) // variant
@Directive({selector: '[divHandle]'}) // variant
export class ChildDirective {
    constructor(elem: ElementRef){}
}

@Component({
    selector: 'my-app',
    ...
})
export class AppComponent implements AfterViewInit {
    @ViewChildren(ChildDirective) childrenContent: QueryList<ChildDirective>;

    ngAfterViewInit(){
        console.log(this.childrenContent);
    }
}

当我记录childrenContent时,我得到一个QueryList对象,但它是空的,没有任何元素可以从中获取信息。

我尝试了多个@Directive选择器,并且我的QueryList始终为空。

2 个答案:

答案 0 :(得分:5)

您可以使用$ event属性来处理宽度,高度,偏移等。通过使用此方法,传统的javascript发挥作用如下

HTML代码将为

<div *ngFor="let link of links;" class="div-link" 
             height="100px"
             width="30px"
             (click)="changeActiveLink($event)">
          <h2>{{link}}</h2>
</div>
<div height="height" width="width" id="highlighter">some text</div>

将div元素上方的点击元素处理为

changeActiveLink(value){
    this.height=value.srcElement.parentElement.attributes['height'].value;
    this.width=value.srcElement.parentElement.attributes['width'].value;
    console.log(this.width);
    console.log(this.height); 
  }

注意:在上面的示例中,click事件位于字母上,因此我们将srcElement作为h2,因此我使用的是parentElement。实时您可以使用方法中的if条件处理它。

你也可以使用console.log点击被点击的元素并获得更多想法来实现这一目标。

<强> LIVE DEMO

答案 1 :(得分:0)

您可以在要弄乱的元素上放置一个句柄..

<div #handle ..>

然后在组件类中,您可以使用@ViewChild注释访问组件。

然后在你的ngOnViewInit中你可以做..

ngOnViewInit() {
  viewChildEl.offsetLeft = 100;
}

应该指出正确的方向。