为什么需要ElementRef
Angular一直在做的一件事情就是降低视图层和应用层之间的耦合,在应用层直接操作DOM,会导致应用层和视图层之间强耦合,导致我们不能将应用运行在不同的环境中。比如令js能够实现多线程的webWorker,在webWorker中,却不能直接操作DOM,angular为我们封装了一个对象,叫做ElementRef,能够获取到视图层中的native对象,比如在浏览器中,native对象就是DOM对象。
以下是Angular中的ElementRef的具体实现:
export class ElementRef {
public nativeElement: any;
constructor(nativeElement: any) { this.nativeElement = nativeElement; }
}
如何使用ElementRef
下面来看一个简单的例子,我们声明一个组件,我们要实现的功能是,点击点击按钮,根据输入框的输入值来更改子组件的颜色。
那么整个组件大概会是这个样子。
首先我们编写app.ts,也就是图上的parent component。
app.ts
import { Child } from './child.component';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector:'app',
template:`<div>
<input #colorIndex type='text' />
<button (click)='changeColor(colorIndex.value)'>change color</button>
<child></child>
</div>`,
directives:[Child]
})
export class App{
private defaultColor:string;
private targetColor:string;
constructor(private elementRef:ElementRef){
//默认颜色初始化
this.defaultColor = 'transparent';
}
//change color
changeColor(value:string):void{
console.log(value);
this.targetColor = this.defaultColor || value;
let Div = this.elementRef.nativeElement.querySelector('child div');
Div.style.backgroundColor = value;
}
}
bootstrap(App);
下面是子组件的代码,没有任何功能,只是简单的声明了一下样式。
child.component.ts
import { Component } from '@angular/core';
@Component({
selector:"child",
template:`<div></div>`,
styles:[`
div{
width:100px;
height:100px;
}
`]
})
export class