嘿,我现在正在学习Angular 2一步,我已经构建了一个结构性自定义指令,除非打电话。除非与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>
我的主组件中有一个字段,该字段称为开关,每次点击按钮,我都会遍历这样的开关的值:
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) { }
}
对于条件= true,我将templateref添加到我的嵌入式视图中,否则我清除了ViewContainerRef。现在我的问题是基本的,什么是ViewContainerRef,它指向带有容器ID的DIV?也许这是文档对象。我无法弄清楚ViewContainerRef所指的位置。
我知道,像NGIF这样的每个结构指令都列入以下内容:
<template [ngIf]=”condition”>
<p>My Content</p>
</template>
因此,我知道templateref是指上面的模板元素,但是我不明白viewContainerRef的位置?
我试图打印ViewContainerRef,而我所得到的只是我不知道它来自何处的评论。
将 ViewContainerRef
视为锚点在DOM中,您可以通过编程方式插入/删除模板和组件。
在您的情况下,该锚点的位置确实是<div *unless>
位置的点。但是不要将其视为DOM节点或一个标记。这是一个角度的概念,所以它实际上没有等效。
真的只是一个容器,您可以通过编程方式控制其内容。
https://angular.io/docs/ts/latest/api/core/index/viewcontainerref-class.html