当我将 *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
和viewContainerRef
创建的。您可以在使用 ViewContainerRef 探索 Angular DOM 操作技术中阅读有关它们的更多信息。
嵌入视图类似于为组件创建的宿主视图。视图包含您在组件模板或ng-template
标记内看到的所有节点。因此,嵌入式视图就像没有组件类的组件模板。下面是结构指令如何创建嵌入视图的几个示例。
纳奇夫
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);
}
}
}
}
纳福
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是Angular实现和扩展模板标签的方式。
由于所有的结构指令,以*开头的指令,如*ngIf,*ngFor等,都在改变DOM,它实际上一直在幕后使用ng模板。放置在元素上的指令只是对此的一些语法糖。
else 块不适用于任何其他元素,因为它需要在需要时添加,因此它必须在 ng 模板中。
以下是有关此内容的更多信息。
当您想根据条件及其反向显示或隐藏模板的一部分时,<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">Text to show</div>
<div *ngIf="!show>Alternate text while primary text is hidden</div>
这样做的好处是,您可以隔离模板的一部分并在需要时"激活"它,就像 plein 对 JS 所做的那样。你可以把它放在不总是放在后面。它为您提供了更结构化的代码。 还有(我认为自 Angular 4.3 以来(<..*ngIf="condition"; then #template1 else #template2>
也非常"方便"。
这是一个部分答案 - 对于类。但是在一个地方链接到相关信息。 我可以给你一些细节和另一个类似的概念.<ng-template>
是一个占位符,不仅适用于 *ngIf 的其他部分,也适用于 *NgFor
<ng-container>
是类似的东西,你没有问过,但稍后在处理内容投影时会遇到。Josh Morony在Youtube上提供了一段关于此的视频。它涉及@ContentChild和@ContentChildren。
Angular Cheatsheet告诉你类的语法。