Angular2:获取模板元素引用的最佳方法是什么

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>)来获取特定元素.您应该尽量避免直接访问,如果可能,请使用绑定.

  • https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ref-vars (4认同)
  • 这些"refs"如何在angular2(`#varName`,在本例中)中工作?它们是特定于角度2的构造吗?它们是添加ID的快捷方式吗?当组件编译为库存HTML时,它是否会消失?我似乎无法找到任何官方文件. (3认同)
  • 它叫做模板变量.这从未添加到DOM,但仅由Angular2使用.它允许您轻松地从模板中的绑定表达式和compinents类中的`ViewChild`和`ContentChild`引用DOM元素.我不知道文档中的哪个地方更多地解释了depht. (3认同)