什么是ng-template,为什么我要绑定* ngIf否则? [英] What is ng-template and why do I bind *ngIf then else to it?
问题描述
当我将* ngIf与then和/或else语句一起使用时,为什么必须绑定到附加到ng-template
元素的模板变量?例如:
When I use *ngIf with a then and/or else statement, why do I have to bind to a template variable that is attached to a ng-template
element? For example:
这有效:
<div *ngIf="show; else elseBlock">Text to show</div>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
但这不起作用:
<div *ngIf="show; else elseBlock">Text to show</div>
<div #elseBlock>Alternate text while primary text is hidden</div>
我还注意到添加一个类也不起作用:
I also noticed adding a class does not work either:
<ng-template #elseBlock class="my-class">
Alternate text while primary text is hidden
</ng-template>
ng-template
有什么特别之处?有什么不同?
What's so special about the ng-template
? How is it different?
推荐答案
这是因为Angular中的所有结构性指令都会创建嵌入式视图.同时使用templateRef
和viewContainerRef
创建一个嵌入式视图.您可以在使用ViewContainerRef 探索Angular DOM操作技术中了解有关它们的更多信息.
This is because all structural directives in Angular create embedded views. An embedded view is created using both templateRef
and viewContainerRef
. You can read more about them in the Exploring Angular DOM manipulation techniques using ViewContainerRef.
嵌入式视图类似于为组件创建的主机视图.视图包含您在组件模板中或ng-template
标记内看到的所有节点.因此,嵌入式视图就像没有组件类的组件模板.以下是一些结构指令如何创建嵌入式视图的示例.
An embedded view is similar to host views that are created for components. A view contains all the nodes that you see in the component template or inside the ng-template
tag. So embedded view is like a component template without the component class. Here are the few examples of how structural directives create embedded views.
private _updateView() {
if (this._context.$implicit) {
...
if (this._thenTemplateRef) {
this._thenViewRef =
// here embedded view is created
this._viewContainer.createEmbeddedView(this._thenTemplateRef, this._context);
}
}
} else {
if (!this._elseViewRef) {
...
this._elseViewRef =
// here embedded view is created
this._viewContainer.createEmbeddedView(this._elseTemplateRef, this._context);
}
}
}
}
ngFor
private _applyChanges(changes: IterableChanges<T>) {
const insertTuples: RecordViewTuple<T>[] = [];
changes.forEachOperation(
(item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
if (item.previousIndex == null) {
// here embedded view is created
const view = this._viewContainer.createEmbeddedView(
this._template, new NgForOfContext<T>(null !, this.ngForOf, -1, -1), currentIndex);
这篇关于什么是ng-template,为什么我要绑定* ngIf否则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!