获取元素的引用

时间:2016-08-03 10:28:00

标签: typescript angular

了解事情是如何运作的。

假设我有同伴代码

<my-element #ref></my-element>
<button (click)="ref.classList.add("prettify")"></button>

它会抛出错误,因为ref会返回MyElement的实例。

如何将<my-element>作为dom元素?我被迫在课堂上ElementRef继续ref.el.classList.add(...)吗?

我也尝试使用表单元素

<form #ref></form> // return a ref about the element
<form #ref="ngForm"></form> return a ref about NgForm 

1 个答案:

答案 0 :(得分:1)

@ViewChild 可用于获取元素引用,如下所示。

<my-element #ref></my-element>

//<---<button (click)="ref.classList.add("prettify")"></button> I don't understand purpose of having this line. What does button do?

在Component中,

import {ViewChild,ElementRef} from '@angular/core';

export class AppComponent{

   @ViewChild('ref') ref:ElementRef;

   ngAfterViewInit(){
     console.log(this.ref.nativeElement);
   }
}

DEMO:https://plnkr.co/edit/uP7CYM?p=preview