Jan*_*cak 24 javascript angular
假设我在Angular 2中有一个这样的组件.
@Component ({
directives: [Timeline, VideoPlayer],
template: `<div>
<span id="myId"></span>
<videoplayer [mode]="mode"></videoplayer>
<timeline [mode]="mode"></timeline>
</div>`,
})
export class VideoEditor {
}
Run Code Online (Sandbox Code Playgroud)
如何从模板中获取对元素的引用?例如,我如何获得对<span>?的引用?
到目前为止我找到了两种方法:
1)使用ElementRef获取参考
export class VideoEditor {
constructor (private el: ElementRef) {
el.nativeElement.getElementsBy.....;
}
}
Run Code Online (Sandbox Code Playgroud)
2)使用ViewChild
export class VideoEditor {
@ViewChild(Timeline) timeline: Timeline;
ngAfterViewInit () {
this.timeline;
}
}
Run Code Online (Sandbox Code Playgroud)
3)使用本地模板变量
1)我不喜欢第一种方法是我需要做类似getElementsBy...功能.
2)关于第二个,我不知道如何访问HTML元素,我只能访问另一个子组件.如果我有更多相同类型的子组件怎么办?
3)本地模板变量只能在模板中使用,对吗?
在Angular 2中获取模板引用的最佳方法是什么?我想要像React这样的东西有 https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
<input ref="myInput" />
Run Code Online (Sandbox Code Playgroud)
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 36
当您有多个相同类型时,可以使用@ViewChild('varName')模板变量(<tag #varName>)来获取特定元素.您应该尽量避免直接访问,如果可能,请使用绑定.
| 归档时间: |
|
| 查看次数: |
57863 次 |
| 最近记录: |