2016-08-03 117 views
0

只为了解事情的工作原理。获取元素的参考

让说我有fellowing代码

<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

@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? 
在组件

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

+0

'Button'仅仅是例子 – efxzsh

+0

感谢演示,但如果引用不是呈现又一个元素(如发生什么事在'* ngIf'中) – efxzsh

+0

NgIf从dom中删除元素。然后,如果你要求这样的DOM元素(技术上不存在),它会抛出一个错误。 – micronyks