Javascript 没有“*”的结构指令?

Javascript 没有“*”的结构指令?,javascript,angular,Javascript,Angular,我有一个简单的指令myNgIf,它是ngIf的基本简化: import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[myNgIf]' }) export class MyNgIfDirective { constructor( private templateRef: TemplateRef<any>, p

我有一个简单的指令
myNgIf
,它是
ngIf
的基本简化:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
  selector: '[myNgIf]'
})
export class MyNgIfDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set myNgIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

}
<div myNgIf="true">
   hello
 </div>
但后来我想,如果我希望它也能工作,但不使用
*

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
  selector: '[myNgIf]'
})
export class MyNgIfDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef) { }

  @Input() set myNgIf(condition: boolean) {
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

}
<div myNgIf="true">
   hello
 </div>

你好
我已经注入了
ViewContainerRef
,所以我有一个锚定“注入到哪里”

但现在我没有“注射什么”

问题:

出于学习目的,我如何引用应用myNgIf的当前元素

NB
我已经知道,我将在开始时看到内容,因为div是一个浏览器已知的已解析元素,而ng template不是,但再一次,我是出于学习目的

以下是我的解决方案:

Renderer2
用于直接访问DOM。 我用注释标记contentdom节点,并在指令加载后将其分离。然后,如果条件的计算结果为true,则稍后将重新附加该条件


免责声明:这真的很难看,还没有准备好生产;-)

如何引用myNgIf应用到的当前元素?
是否尝试注入
ElementRef
@yurzui是的,我考虑过,但我想通过
this.viewContainer.createEmbeddedView
有条件地显示/隐藏内容。问题是,
createEmbeddedView
采用了我没有的tempalte(因为它现在没有被卸载到模板中)。我们无法手动创建TemplateRef。它使用在过程中创建的内部数据compilation@yurzui好的,那么有没有一种非*-方法可以做到:?总是有方法可以做错事:)顺便问一下,你为什么要使用
pipe(map(
)而不是
map
?(要求学习)这是你现在真正应该经常使用的可管道语法:
<div myNgIf="true">
   hello
 </div>