【发布时间】:2020-12-25 03:18:15
【问题描述】:
正如标题所说,我一直在尝试(并且到目前为止)学习 Angular,直到我进入结构指令。
我必须使用 TemplateRef 和 ViewContainerRef 创建自己的。
课程老师是这样做的:
import { Directive, TemplateRef, Input, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
@Input() set appUnless(condition: boolean)
{
if(!condition)
{
console.log(this.templateRef);
console.log(this.vcRef);
this.vcRef.createEmbeddedView(this.templateRef);
}
else
{
console.log(this.templateRef);
console.log(this.vcRef);
this.vcRef.clear();
}
}
constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) { }
}
<div class="container">
<div class="row">
<div class="col-xs-12">
<button
class="btn btn-primary"
(click)="onlyOdd = !onlyOdd">Only show odd numbers</button>
<br><br>
<ul class="list-group" *appUnless="onlyOdd">
<li
class="list-group-item" *ngFor="let number of numbers">
{{number}}
</li>
</ul>
<ng-template>
<p>Only odd</p>
</ng-template>
</div>
</div>
</div>
console.log 行是我插入的,所以我可以看到发生了什么。
不幸的是,我只是不知道这段代码是如何工作的。
我也一直在尝试使用 Angular 文档,但我似乎并没有真正理解。
到目前为止我所理解的(我不确定它是否正确)是 TemplateRef 只是一个引用,它将从指令中的 * 创建,而 ViewContainerRef 要么显示它,要么不显示它,通过方法例如 createEmbeddedView() 或 clear()。
谁能向我深入解释一下代码的作用,主要是 TemplateRef 和 ViewContainerRef? 谢谢。
【问题讨论】:
-
结构指令负责 HTML 布局。它们通常通过添加、删除或操作元素来塑造或重塑 DOM 的结构。简单来说,
TemplateRef是对模板的引用,即附加指令的视图(在您的情况下,它是ul)。而ViewContainerRef,顾名思义,就是存放您视图的容器。而且您基本上会从容器(即 DOM)中切换(附加和删除)模板(视图)。 -
将其写为答案,以便我接受。您能否详细说明一下“而 ViewContainerRef,顾名思义,是容纳您的视图的容器。”?这是否意味着我来自该组件的整个 HTML 文件都存储在这个 ViewContainerRef 中?
标签: angular