[英]How can I set a class to a HTML element which is created by custom tooltip function?
[英]How can I set the id of an element, which is created by ngFor?
我創建了一些元素:
<span *ngFor="let versuch of versuche">
<div id="titleId[versuch]"><br></div>
</span>
titleId
是一個字符串列表,其中存儲了我的元素 ID)。
但是,如果我嘗試使用document.getElementById('__title__5')
訪問元素,則找不到該元素(__title__5 是元素 ID 之一)。
那么你知道一種方法來設置每個代碼的 id 嗎?
ngAttr
用於綁定到任意屬性 AngularJS
例如,考慮這個模板
<span *ngFor="let versuch of versuche">
<div ng-attr-id="{{ 'titleId-' + versuch }}"><br></div>
</span>
文檔 - https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes
角
<li *ngFor="item of items" #elem [attr.id]="item.id">
{{ item.name}} ID: {{elem.id}}
</li>
使用*ngFor
index
。 嘗試以下
選項 1 - titleId
是一個字符串數組
<span *ngFor="let versuch of versuche; let i=index">
<div attr.id="{{titleId[i]}}"><br></div>
</span>
選項 2 - 未使用titleId
如果您需要根據versuche
變量的索引有相應的 id,您可以跳過變量titleId
並直接在模板中進行。
<span *ngFor="let versuch of versuche; let i=index">
<div [attr.id]="'__title__' + i">{{versuch}}<br></div>
</span>
選項 3 - titleId
是一個對象
如果titleId
是一個對象,其鍵對應於每個versuche
,則以下應該有效
成分
versuche = [ 'versuche_1', 'versuche_2', 'versuche_3' ];
titleIdObj = {
'versuche_1': '__title__1',
'versuche_2': '__title__2',
'versuche_3': '__title__3',
}
模板
<span *ngFor="let versuch of versuche">
<div attr.id="{{titleIdObj[versuch]}}">{{versuch}}<br></div>
</span>
工作示例: Stackblitz
使用 [id] 代替 id,如下例所示:
<span *ngFor="let versuch of versuche">
<div [id]="titleId[versuch]"><br></div>
</span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.