嘿,我现在正在学习角2一步一步,我已经建立了一个结构自定义指令,它被称为除非。除非执行与ngIf相同的操作,否则,如果我的条件为true,则将元素附加到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,对于每点击一个按钮,我都会像这样遍历开关的值:
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,我将临时文件添加到我的embeddedView中,否则就清除viewContainerRef。现在我的问题是基本的,什么是viewContainerRef,它指向带有容器id的div吗?或者这可能是文档对象。我不知道viewContainerRef指的是哪里。
我知道像ngIf这样的每一个结构指令都是desugar,如下所示:
<template [ngIf]=”condition”>
<p>My Content</p>
</template>
因此,我知道templateRef是指上面的模板元素,但是我不知道viewContainerRef指向哪里?
我试着打印viewContainerRef,我得到的只是一个评论,我不知道它是从哪里来的。
发布于 2017-02-25 10:35:18
将ViewContainerRef
看作DOM中的锚点,您可以在其中以编程方式插入/删除模板和组件。
在您的例子中,那个锚点的位置确实是<div *unless>
所处的位置。但是,不要将其视为DOM节点或标记。它是一个角度的概念,所以它没有真正的等效。
实际上,它只是一个容器,您可以通过编程方式控制它的内容,。
https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html
https://stackoverflow.com/questions/42459248
复制