javascript - ViewContainerRef 服务以及它引用哪个元素?(Angular 2)

标签 javascript angular

嘿,我现在正在逐步学习 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/

相关文章:

javascript - 想获取标记的 infobubble 的内容?

javascript - 使用空数组时比较运算符 JavaScript 的奇怪行为

validation - 在 Angular 2 中,如何在使用模板驱动表单时设置异步验证器?

javascript - 在 Angular 2上传图像后,显示404未找到

javascript - 将元素 (SVG) 传递给网络 worker

javascript - 谁能解释这段 Javascript 中发生了什么?

javascript - 如何使用 javascript 创建带有字符串路径列表的动态树结构

angular - 如何转换为可编辑的选择框?

javascript - 回调在 Angular2/Firebase 中生成 "TypeError: this is undefined"

javascript - 通过服务在组件之间共享信息不起作用