簡體   English   中英

ViewContainerRef服務及其引用的元素?(角度2)

[英]ViewContainerRef service and to which element does it refer to?(Angular 2)

嘿,我現在正在逐步學習“角度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,每次單擊按鈕時,都會遍歷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是指上面的template元素,但是我不明白viewContainerRef指向哪里?

我試圖打印viewContainerRef,但我得到的只是一條注釋,我不知道它來自哪里。

ViewContainerRef視為DOM中的錨點 ,您可以在其中以編程方式插入/刪除模板和組件。

在您的情況下,該錨點的位置確實是<div *unless>所在的點。 但是不要將其視為DOM節點或標記。 這是一個Angular概念,因此實際上沒有等效概念。

確實,這只是一個您可以通過編程控制其內容容器

https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM