Html 从Angular4中生成的li引用元素属性
我用Html 从Angular4中生成的li引用元素属性,html,angular,Html,Angular,我用*ngFor生成了一个简单的待办事项列表,我正在尝试获取li的offsetTop值。对于第一个生成的li,我可以做得很好,但是我需要能够为任何li及其属性设置一个变量。是否有某种形式的索引可以用于模板变量以实现“this”效果 我的模板: <li class="search-item" #todoli *ngFor="let todoItem of todos; let item=index " (click)="selectTodo($event, todoItem)" &g
*ngFor
生成了一个简单的待办事项列表,我正在尝试获取li
的offsetTop
值。对于第一个生成的li,我可以做得很好,但是我需要能够为任何li及其属性设置一个变量。是否有某种形式的索引可以用于模板变量以实现“this”效果
我的模板:
<li class="search-item" #todoli
*ngFor="let todoItem of todos; let item=index "
(click)="selectTodo($event, todoItem)"
>
<span class="todo-item">{{ todoItem.name }}</span>
<span class="delet-todo" (click)="deleteTodo(item)">✕</span>
</li>
ViewChild
应该查询单个子级。应用于查询多个子项:
@ViewChildren("todoli")
todolis: QueryList<any>;
@ViewChildren(“托多利”)
todolis:QueryList对象。ViewChild
应该查询单个子对象。应用于查询多个子项:
@ViewChildren("todoli")
todolis: QueryList<any>;
@ViewChildren(“托多利”)
todolis:QueryList对象。您也可以在不使用任何ViewChild/ViewChildren
引用的情况下执行此操作:
<li class="search-item" #todoli
*ngFor="let todoItem of todos; let item=index "
(click)="selectTodo($event, todoItem, todoli)"
>
selectTodo(event, i, todoli) {
this.selectedItem = i;
this.li = todoli;
console.log(this.li.offsetTop);
}
您也可以在不使用任何ViewChild/ViewChildren
引用的情况下执行此操作:
<li class="search-item" #todoli
*ngFor="let todoItem of todos; let item=index "
(click)="selectTodo($event, todoItem, todoli)"
>
selectTodo(event, i, todoli) {
this.selectedItem = i;
this.li = todoli;
console.log(this.li.offsetTop);
}
@BenediktSchmidt为什么提供使用private field?因为我试图在自己的项目中使用ViewChildren来检查这是否有效,当我打印列表时,我看到该字段包含数组。我不确定这是否是一个糟糕的做法,但我只是认为它的工作,那么为什么呢not@BenediktSchmidt应该用toArray()访问它,或者用其他QueryList方法遍历它。好的,那么我收回我的评论, sorry@BenediktSchmidt为什么提供使用私有字段?因为我试图在我自己的项目中使用ViewChildren来检查这是否有效,当我打印列表时,我看到字段保存了数组。我不确定这是否是一个糟糕的做法,但我只是认为它的工作,那么为什么呢not@BenediktSchmidt应该用toArray()访问它,或者用其他QueryList方法遍历它。好吧,那么我收回我的评论,对不起,我今天几乎放弃了尝试如何引用元素。感谢您不仅回答了我的问题,而且向我展示了获取我所需的最简单的方法!现在我将阅读$event,它似乎是我一直缺少的图片。今天我几乎放弃了尝试如何引用元素。感谢您不仅回答了我的问题,而且向我展示了获取我所需的最简单的方法!我现在将阅读$event,它似乎是我一直缺少的图片。