[英]How to get attribute value inside li tag?
I am using angular 6 application where i am passing data through attribute, 我正在使用angular 6应用程序,通过属性传递数据,
First i have given [attr.parent_id]
in ul tag like, 首先,我在ul标签中给出了
[attr.parent_id]
,
<ul class="list-unstyled" id="1" [attr.parent_id]="123"></ul>
For which i have used, console.log(target.getAttribute('parent_id'));
我使用过的
console.log(target.getAttribute('parent_id'));
And the result displays 123
. 并且结果显示
123
。
Like same thing i need to get a index number from li
tag like of the same ul
, 就像同一件事一样,我需要从
li
标记中获取索引编号,例如同一ul
,
<ul class="list-unstyled" id="1" [attr.parent_id]="123">
<li class="media p-2 column" *ngFor="let item of items;let i = index;" [attr.child_id]="i"></li>
</ul>
Here i have given [attr.child_id]
to retrieve the index position and i have used console.log(target.getAttribute('child_id'));
在这里,我给了
[attr.child_id]
来检索索引位置,并且我使用了console.log(target.getAttribute('child_id'));
. 。
This console of getting child_id
displays the value as null . 这个获取
child_id
控制台将值显示为null 。
The ul tag gives me the value of attribute but li tag is returning null as result. ul标签为我提供了attribute的值,但li标签返回的结果为null。
The StackBlitz link was https://stackblitz.com/edit/angular-oaghq3 StackBlitz链接为https://stackblitz.com/edit/angular-oaghq3
Kindly help me to set and get the attribute to li tag and to retrieve data. 请帮助我设置并获取li标签的属性并检索数据。
You can query the elements by using the ViewChildren
decorator as showcased in this blitz 您可以使用闪电战中展示的
ViewChildren
装饰器来查询元素
<ul class="list-unstyled" id="list" [attr.parent_id]="123">
<li #li class="media p-2 column" *ngFor="let item of items;let i = index;" [attr.child_id]="i"> {{item.name}} </li>
</ul>
@ViewChildren("li") listElements: QueryList<ElementRef<HTMLLIElement>>;
private printElements() {
const elements = this.listElements.toArray();
elements.forEach(element => {
const isLiElemenet = element.nativeElement instanceof HTMLLIElement;
const child_id = element.nativeElement.getAttribute('child_id');
console.log({ isLiElemenet, child_id });
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.