Car*_*ina 2 javascript angular queryselector
我有一个列表,其中每个li都有独特的data-id.
<ul class="list">
<li class="list__el"
*ngFor="let item of cars"
data-id="{{ item.id }}">
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
在 JS 中我会写
let myLi = document.querySelector(`.list__el[data-id="${item.id}"]`)
Run Code Online (Sandbox Code Playgroud)
如何为 Angular 正确重写它?
使用@ViewChildren模板参考,例如#listItem.
@Component({
template: `<ul class="list">
<li #listItem class="list__el"
*ngFor="let item of cars"
data-id="{{ item.id }}">
</li>
</ul>`
})
export component MyComponent implements AfterViewInit {
// Note that the parameter here relates to the #listItem in the template.
@ViewChildren('listItem')
public listItems!: QueryList<ElementRef<HTMLLIElement>>
public ngAfterViewInit() {
console.log(
this.listItems.find(itm =>
itm.nativeElement.getAttribute('data-id') === 'my-element-id'
)
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8977 次 |
| 最近记录: |