嘿,我现在正在逐步学习 Angular 2,并且我已经构建了一个名为 except 的结构自定义指令。 除非行为与 ngIf act 相同,否则如果我的条件为真,则将元素附加到 dom,否则将其分离。 这是我操作指令的模板:
<h1>Structural Custom Directive</h1>
<h2>*unless</h2>
<div id="container">
<div *unless="switch" id="conditional-text">Conditional Text</div>
</div>
<button (click)="onSwitch()">Switch</button>
我的主要组件中有一个名为 switch 的字段,每次单击按钮时,我都会像这样遍历 switch 的值:
onSwitch(){
this.switch = !this.switch;
}
现在指令的代码如下:
import { Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
@Directive({
selector: '[unless]'
})
export class UnlessDirective {
@Input() set unless(condition: Boolean){
if (condition){
this.vcRef.createEmbeddedView(this.templateRef);
}else{
this.vcRef.clear();
}
console.log('this.vcRef', this.vcRef);
console.log('this.templateRef', this.templateRef);
}
constructor(private templateRef: TemplateRef<any>,private vcRef: ViewContainerRef) { }
}
对于condition=true,我将templateref 添加到我的embeddedView,否则我清除viewContainerRef。 现在我的问题是基本的,什么是viewContainerRef,它是否指向具有容器id的div?或者这可能是文档对象。 我无法弄清楚 viewContainerRef 所指的位置。
我知道像 ngIf 这样的每个结构指令都被脱糖为以下内容:
<template [ngIf]=”condition”>
<p>My Content</p>
</template>
因此我知道 templateRef 是指上面的模板元素,但我不明白 viewContainerRef 指向哪里?
我尝试打印 viewContainerRef,但得到的只是一条注释,我不知道它来自哪里。
最佳答案
想想ViewContainerRef
作为 DOM 中的 anchor ,您可以在其中以编程方式插入/删除模板和组件。
在您的情况下,该 anchor 的位置确实是 <div *unless>
所在的点。位于。但不要将其视为 DOM 节点或一段标记。这是一个 Angular 概念,因此实际上没有等效的概念。
实际上,它只是一个容器,您可以通过编程方式控制其内容。
https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html
关于javascript - ViewContainerRef 服务以及它引用哪个元素?(Angular 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42459248/