// html
<p #p>some text</p>
// js
@ViewChild('p') pRef: ElementRef
複製代碼
可經過pRef.nativeElement
拿到原生節點html
// html
<ng-template #container>some text</ng-template>
// js
@ViewChild('container') conRef: TemplateRef
複製代碼
未渲染前以註釋節點佔位bash
// html
<div #div>some text</div>
// js
@ViewChild('div', {read: ViewContainerRef}) divVcRef: ViewContainerRef;
複製代碼
能夠將其理解爲一塊視圖容器,經過下面兩種方法能夠往視圖中添加DOMapp
TemplateRef
ComponentFactory
默認行爲===appendChild,修改index可改變插入位置ui
生成factory:this
import { ComponentFactoryResolver } from '@angular/core'
import { ComponentA } from 'xxx'
...
insert() {
const factory = this.comFR.resolveComponentFactory(ComponentA)
this.divVcRef.createComponent(factory)
}
複製代碼
由Factory生成的組件引用,常見的應用是建立Modalspa
const factory = this.cfr.resolveComponentFactory(ComfirmModalComponent);
const componentRef = factory.create(this.injector)
this.instanceRef = componentRef;
componentRef.instance.isShow = true;
this.appRef.attachView(componentRef.hostView);
document.body.appendChild( (componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0])
複製代碼
與Vue的Slot相似,可插入DOM or Component,支持多插槽code
// ChildComponent
<div class="panel panel-primary">
<div class="panel-heading">
<ng-content select="h3"></ng-content>
</div>
<div class="panel-body">
<ng-content select="child2"></ng-content>
</div>
<div class="panel-footer">
<ng-content select="p"></ng-content>
</div>
</div>
// ParentComponent
<child>
<h3>這是父層投影進來的內容</h3>
<child (sayhello)="doSomething()"></child>
<p>這是底部內容</p>
</child>
複製代碼
@ContentChild(Child2) child2Com: Child2Component
複製代碼