当我将 *ngIf 与 then 和/或 else 语句一起使用时,为什么我必须绑定到附加到ng-template
元素?例如:
这有效:
<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>
我还注意到添加一个类也不起作用:
<ng-template #elseBlock class="my-class">
Alternate text while primary text is hidden
</ng-template>
有什么特别之处ng-template
?有什么不同?
这是因为 Angular 中的所有结构指令都会创建嵌入视图。使用两者创建嵌入视图templateRef
and viewContainerRef
。您可以在以下位置阅读有关它们的更多信息使用 ViewContainerRef 探索 Angular DOM 操作技术 https://hackernoon.com/exploring-angular-dom-abstractions-80b3ebcfc02.
嵌入视图类似于为组件创建的宿主视图。视图包含您在组件模板中或在组件模板中看到的所有节点ng-template
标签。所以嵌入视图就像一个没有组件类的组件模板。以下是结构指令如何创建嵌入视图的几个示例。
ngIf
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)