Angular2:什么是得到一个模板元素的参考
问题描述:
比方说,最好的办法我已经在角2Angular2:什么是得到一个模板元素的参考
@Component ({
directives: [Timeline, VideoPlayer],
template: `<div>
<span id="myId"></span>
<videoplayer [mode]="mode"></videoplayer>
<timeline [mode]="mode"></timeline>
</div>`,
})
export class VideoEditor {
}
这样的组件怎样才能从模板的元素的引用?例如,我如何获得对<span>
的参考?
我发现两种方法迄今:
1)获取使用参考ElementRef
export class VideoEditor {
constructor (private el: ElementRef) {
el.nativeElement.getElementsBy.....;
}
}
2)使用ViewChild
export class VideoEditor {
@ViewChild(Timeline) timeline: Timeline;
ngAfterViewInit() {
this.timeline;
}
}
1)我不喜欢第一种方法是我需要做类似getElementsBy...
的功能。
2)关于第二个,我不知道如何获得一个HTML元素的访问权限,我只能访问另一个子组件。如果我有更多的同一类型的子组件呢?
3)本地模板变量只能在模板中使用,对吗?
在Angular 2中获取对模板的引用的最佳方式是什么? 我想有东西等反应具有 https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
<input ref="myInput" />
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
答
可以使用@ViewChild('varName')
与模板变量(<tag #varName>
)来得到一个特定的元素,当你有一个以上相同的类型。 你应该尽量避免直接访问,如果可能的话,使用绑定。
感谢您的回答,请您详细介绍一下如何使用绑定进行操作?你是什么意思? –
这取决于您实际想要对标记进行的引用。对于绑定,我的意思是''。 –
假设我想关注''。最好的办法是做'@ViewChild('keywordInput')keywordInput;'然后'this.keywordInput.nativeElement.focus();'我是对吗?对不起,这有点超出了我的问题范围。 –