Angular2:如何最好地获取模板元素的引用?
Angular2:如何最好地获取模板元素的引用?
这个问题已经有了答案:
假设我在Angular 2中有一个组件像这样。
@Component ({ directives: [Timeline, VideoPlayer], template: ` `, }) export class VideoEditor { }
如何从模板中获取一个元素的引用?例如,如何获取一个的引用?
到目前为止,我找到了两种方法:
1)使用ElementRef获取引用
export class VideoEditor { constructor (private el: ElementRef) { el.nativeElement.getElementsBy.....; } }
2)使用ViewChild获取引用
export class VideoEditor { @ViewChild(Timeline) timeline: Timeline; ngAfterViewInit () { this.timeline; } }
3)使用本地模板变量获取引用
1)我不喜欢第一种方法,因为我需要做类似getElementsBy...
的函数。
2)关于第二种方法,我不知道如何访问HTML元素,我只能访问另一个子组件。如果我有多个相同类型的子组件怎么办?
3)本地模板变量仅在模板内起作用,我是正确的吗?
在Angular 2中获取模板引用的最佳方法是什么?我想要像React一样的东西https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute
var input = this.refs.myInput; var inputValue = input.value; var inputRect = input.getBoundingClientRect();
(翻译:两个带粗体字的段落,之间有一条水平线。)
admin 更改状态以发布 2023年5月24日