Dre*_*rew 3 angular2-directives angular
我有一个模板创建一个链接列表使用*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>
Run Code Online (Sandbox Code Playgroud)
这导致了如下结构:
<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>
Run Code Online (Sandbox Code Playgroud)
我希望我的荧光笔div来获得的宽度Link 1时activeLink = 0.类似于这个普通的js:
var High = document.getElementById('highlighter');
High.style.width = document.getElementsByClass('div-link')[0].children[activeLink].offsetWidth; //activeLink = 0
Run Code Online (Sandbox Code Playgroud)
在我的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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我记录childrenContent我得到一个QueryList对象,但它是空的,没有从中获取信息的元素.
我尝试了几个@Directive选择器,总是QueryList空的.
您可以使用$ 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>
Run Code Online (Sandbox Code Playgroud)
将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);
}
Run Code Online (Sandbox Code Playgroud)
注意:在上面的示例中,click事件在字母上,因此我们将获得srcElement,h2因此我使用parentElement.实时您可以使用方法中的if条件处理它.
你也可以在console.log中点击被点击的元素,并获得更多想法来实现这一目标.
| 归档时间: |
|
| 查看次数: |
9768 次 |
| 最近记录: |