【发布时间】:2017-07-21 10:23:16
【问题描述】:
我有一个模板,它使用*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 在activeLink = 0 时获得Link 1 的宽度。类似于这个普通的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 总是为空。
【问题讨论】:
-
嘿伙计,你看到我的回答了吗?
标签: angular angular2-directives