Com*_*ode 25 angular2-directives angular2-template angular
我有动态生成的输入:
<div *ngFor="let cell of column; let i = index;">
<!-- Material design input-->
<md-input id="my-input-{{i}}">
</md-input>
</div>
Run Code Online (Sandbox Code Playgroud)
请注意id=my-input-{{i}}
我希望基于此动态ID获得对DOM元素的引用.此输入可以是3个,6个或更多输入,因此我需要动态访问id并保持它.
Dav*_* F. 32
唯一的回应是
let elem:Element = document.getElementById("myProgrammaticallyChosenIndex")
没有其他角度怪异的仪式需要
测试角4+
Sye*_*aqi 10
使用ElementRef
class from @angular/core
获取父元素,然后创建一个HTMLElement
按类名获取其动态元素.
零件:
declare var $: any; //intentional use of jQuery-not recommended though
@Component({
selector: 'my-app',
template: `
<input type='button' (click)='addDiv()' value='Add New Div' />
<input type='button' (click)='selectDiv()' value='Select' />
`
})
export class App {
constructor(private elRef: ElementRef) {
}
addDiv() {
/*intentional use of jQuery for appending new div
give a class to your dynamic elements*/
$('my-app').append("<div class='foo'>Hello I'm Dynamic!</div>");
}
selectDiv() {
//create a new HTMLElement from nativeElement
var hElement: HTMLElement = this.elRef.nativeElement;
//now you can simply get your elements with their class name
var allDivs = hElement.getElementsByClassName('foo');
//do something with selected elements
console.log(allDivs);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我这里jQuery
仅用于快速演示目的.否则,你不应该使用jQuery
带Angular
.
归档时间: |
|
查看次数: |
63475 次 |
最近记录: |