Angular可以运行在不同的平台上--浏览器,移动平台或web worker。因此,站在平台特定的API和框架接口之间需要抽象层次。在Angular中,这些抽象成为以下引用类型的形式:ElementRef,TemplateRef,ViewRef,ComponentRef和ViewContainerRef。在本文中,我们将详细介绍每种引用类型,并展示如何使用它们来操作DOM
@ViewChild
Angular提供 @ViewChild和@ViewChildren装饰器来进行DOM查询。他们的行为是一样的,只是前者返回一个reference
,后者返回一个QueryList对象,该对象包含多个reference
。
通常,这些装饰器与模板引用变量配对使用。模板引用变量只是对模板中的DOM元素的命名引用。您可以将其视为与html元素的id属性类似的东西。用模板引用标记DOM元素,然后使用ViewChild装饰器在类中查询它。这里是基本的例子:
@Component({
selector: 'sample',
template: `
<span #tref>I am span</span>
`
})
export class SampleComponent implements AfterViewInit {
@ViewChild("tref", {read: ElementRef}) tref: ElementRef;
/** AfterViewInit之后@ViewChild才生效 */
ngAfterViewInit(): void {
// outputs `I am span`
console.log(this.tref.nativeElement.textContent);
}
}
ViewChild装饰器的基本语法如下:
@ViewChild([reference from template], {read: [reference type]});
在这个例子中,你可以看到我在html
中指定了tref
作为模板引用名,并且得到与这个元素相关的ElementRef。第二个参数并不是必需的,因为Angular可以通过DOM元素的类型来推断引用类型。例如,如果它是一个简单的HTML元素(如span),那么angular将返回ElementRef。如果它是一个模板元素,它将返回TemplateRef。但是有一些引用,如ViewContainerRef不能被推断,并且必须read
参数中指。还有其他的,比如ViewRef不能从DOM返回,必须手动构造。
ElementRef
这是最基本的抽象。如果你观察它的类结构,你会发现它只保存了它所关联的native element
。对于访问native DOM element
非常有用,如下:
// outputs `I am span`
console.log(this.tref.nativeElement.textContent);
不过,Angular团队不鼓励这种用法。这不仅会带来安全风险,还会在应用程序和渲染层之间造成紧密耦合,这使得在多个平台上运行应用程序变得困难。这种凡是破坏了抽象。后面你会看到,在Angular中实现的DOM操作中几乎不需要这样一个较低级别的访问。
可以使用@ViewChild为任何DOM元素返回ElementRef。但是,由于所有components
都包含在在自定义DOM元素中,并且所有directive
都依附于DOM元素,因此组件和指令类可以通过DI机制获取与其主机元素关联的ElementRef实例:
@Component({
selector: 'sample',
...
export class SampleComponent{
constructor(private hostElement: ElementRef) {
//outputs <sample>...</sample>
console.log(this.hostElement.nativeElement.outerHTML);
}
TemplateRef
模板的概念应该是大多数Web开发人员熟悉的。在整个应用程序的视图中重复使用一组DOM元素。在HTML5标准引入了template
标签之前,大多数都是用下面这种方式实现,增加type
属性:
<script>
let tpl = document.querySelector('#tpl');
let container = document.querySelector('.insert-after-me');
insertAfter(container, tpl.content);
</script>
<div class="insert-after-me"></div>
<ng-template id="tpl">
<span>I am span in template</span>
</ng-template>
Angular支持这种方法,并实现TemplateRef类来处理模板。以下是如何使用它:
@Component({
selector: 'sample',
template: `
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
`
})
export class SampleComponent implements AfterViewInit {
@ViewChild("tpl") tpl: TemplateRef<any>;
ngAfterViewInit() {
let elementRef = this.tpl.elementRef;
// outputs `template bindings={}`
console.log(elementRef.nativeElement.textContent);
}
}
Angular从DOM中删除模板元素,并在其位置插入注释。这是呈现时的样子:
<sample>
<!--template bindings={}-->
</sample>
TemplateRef类本身就是一个简单的类。It holds a reference to its host element in elementRef property and has one method createEmbeddedView。这个方法是非常有用的,因为它允许我们创建一个视图并以ViewRef的形式返回一个引用
ViewRef
Angular鼓励开发人员将UI视为Views的组合,而不是将其视为独立的HTML标记树。
Angular支持2种视图
- Embedded Views which are linked to a Template
- Host Views which are linked to a Component
Creating embedded view
ngAfterViewInit() {
let view = this.tpl.createEmbeddedView(null);
}
Creating host view
constructor(private injector: Injector,
private r: ComponentFactoryResolver) {
let factory = this.r.resolveComponentFactory(ColorComponent);
let componentRef = factory.create(injector);
let view = componentRef.hostView;
}
ViewContainerRef
表示可以附加一个或多个视图的容器。
首先要提到的是,任何DOM元素都可以用作视图容器。通常,ViewContainer
与ng-container
结合使用。ng-container
会被渲染为一个注释,所以它不会在DOM中引入多余的html元素。以下是在组件模板的特定位置创建ViewContainer的示例:
@Component({
selector: 'sample',
template: `
<span>I am first span</span>
<ng-container #vc></ng-container>
<span>I am last span</span>
`
})
export class SampleComponent implements AfterViewInit {
@ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
ngAfterViewInit(): void {
// outputs `template bindings={}`
console.log(this.vc.element.nativeElement.textContent);
}
}
Manipulating views
ViewContainer为操作视图提供了一个方便的API
class ViewContainerRef {
...
clear() : void
insert(viewRef: ViewRef, index?: number) : ViewRef
get(index: number) : ViewRef
indexOf(viewRef: ViewRef) : number
detach(index?: number) : ViewRef
move(viewRef: ViewRef, currentIndex: number) : ViewRef
}
我们之前已经看到,如何从模板和组件手动创建两种类型的视图。一旦我们有了一个视图,我们可以使用插入方法将其插入到DOM中。所以,下面是从模板中创建一个嵌入式视图并将其插入到由ng-container元素标记的特定位置的示例:
@Component({
selector: 'sample',
template: `
<span>I am first span</span>
<ng-container #vc></ng-container>
<span>I am last span</span>
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
`
})
export class SampleComponent implements AfterViewInit {
@ViewChild("vc", {read: ViewContainerRef}) vc: ViewContainerRef;
@ViewChild("tpl") tpl: TemplateRef<any>;
ngAfterViewInit() {
let view = this.tpl.createEmbeddedView(null);
this.vc.insert(view);
}
}
Creating Views
ViewContainer还提供API来自动创建视图:
class ViewContainerRef {
element: ElementRef
length: number
createComponent(componentFactory...): ComponentRef<C>
createEmbeddedView(templateRef...): EmbeddedViewRef<C>
...
}
这些都是我们上面手动完成的简单包装。他们从模板或组件创建一个视图,并将其插入到指定位置。
ngTemplateOutlet and ngComponentOutlet
上面介绍了底层机制,但是Angular提供了2个指令: ngTemplateOutlet
和 ngComponentOutlet
,只需在html(template)
中快速实现创建视图
ngTemplateOutlet
@Component({
selector: 'sample',
template: `
<span>I am first span</span>
<ng-container [ngTemplateOutlet]="tpl"></ng-container>
<span>I am last span</span>
<ng-template #tpl>
<span>I am span in template</span>
</ng-template>
`
})
export class SampleComponent {}
ngComponentOutlet
<ng-container *ngComponentOutlet="ColorComponent"></ng-container>