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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34636435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:39:33  来源:igfitidea点击:

Angular2: What is the best way to get a reference of a template element

javascriptangular

提问by Jan Vorcak

Let's say I have a component like this in Angular 2.

假设我在 Angular 2 中有一个这样的组件。

@Component ({
   directives: [Timeline, VideoPlayer],
   template: `<div>
    <span id="myId"></span>
    <videoplayer [mode]="mode"></videoplayer>
    <timeline [mode]="mode"></timeline>
  </div>`,
})
export class VideoEditor {
}

How can I get a reference to an element from a template? For instance, how do I get a reference to a <span>?

如何从模板中获取对元素的引用?例如,我如何获得对 a 的引用<span>

I found two approaches so far:

到目前为止,我发现了两种方法:

1) Get a reference using ElementRef

1) 使用ElementRef获取引用

export class VideoEditor {    
  constructor (private el: ElementRef) {
    el.nativeElement.getElementsBy.....;
  }
}

2) Using ViewChild

2) 使用ViewChild

export class VideoEditor {  
  @ViewChild(Timeline) timeline: Timeline;  
  ngAfterViewInit () {
    this.timeline;
  }
}

3) Using local template variable

3) 使用本地模板变量



1) What I don't like about a first approach is that I need to do getElementsBy...-like function.

1)我不喜欢第一种方法的是我需要做类似getElementsBy...的功能。

2) Regarding a second one, I don't know how to get an access to a HTML element, I can only get access to another sub-component. And what if I have more subcomponents of a same type?

2) 关于第二个,我不知道如何访问 HTML 元素,我只能访问另一个子组件。如果我有更多相同类型的子组件怎么办?

3) Local template variable only works within a templates, am I right?

3) 本地模板变量只能在模板中使用,对吗?

What is the best way to get a reference to a template in Angular 2? I'd like to have something like React has https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

在 Angular 2 中获取模板引用的最佳方法是什么?我想要像 React 这样的东西 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();

回答by Günter Z?chbauer

You can use @ViewChild('varName')with a template variable (<tag #varName>) to get a specific element when you have more than one of the same type. You should try to avoid direct access anyway, use bindings instead if possible.

当您有多个相同类型时,您可以使用@ViewChild('varName')模板变量 ( <tag #varName>) 来获取特定元素。无论如何,您应该尽量避免直接访问,如果可能,请改用绑定。