Angular2:什么是得到一个模板元素的参考的最佳方法 [英] Angular2: What is the best way to get a reference of a template element

查看:109
本文介绍了Angular2:什么是得到一个模板元素的参考的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有这样的成分角2。

  @Component({
   指令:[时间轴,录像机]
   模板:`< D​​IV>
    &所述;跨度的id =MYID>&下; /跨度>
    <录像机[模式] =模式>< /录像机>
    <时间表[模式] =模式>< /时间表>
  < / DIV>`
})
出口类VideoEditor {
}

我怎样才能得到一个模板的元素的引用?举例来说,我如何得到一个参考<跨度>

我发现两种方法至今:

1),使用获得的参考 ElementRef

 出口类VideoEditor {
  构造函数(私人EL:ElementRef){
    el.nativeElement.getElementsBy .....;
  }
}

2)使用 ViewChild

 出口类VideoEditor {
  @ViewChild(时间轴)时间轴:时间轴;
  ngAfterViewInit(){
    this.timeline;
  }
}

3)使用本地模板变量


1)我不喜欢什么第一种方法是,我需要做的 getElementsBy ... 般的功能。

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

3)本地模板变量仅在模板的作品,对吗?

什么是角2得到一个模板的引用的最好方法?
我想有这样的事情已经作出反应
https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

 <输入REF =myInput/>


  VAR输入= this.refs.myInput;
inputValue的VAR = input.value;
变种inputRect = input.getBoundingClientRect();


解决方案

您可以使用 @ViewChild('的varName')与模板变量(<标签#的varName> )来得到一个特定的元素,当你有相同类型的多个。
你应该尽量避免直接访问反正,而是如果可能的话使用绑定。

Let's say I have a component like this in 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>?

I found two approaches so far:

1) Get a reference using ElementRef

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

2) Using ViewChild

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

3) Using local template variable


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

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?

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

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

<input ref="myInput" />


var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

解决方案

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.

这篇关于Angular2:什么是得到一个模板元素的参考的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆