结构指令 - 找到它所放置的元素

Cal*_*v J 18 angular

使用结构指令,我如何获得指令所在的(本机)元素?使用普通指令,ElementRef具有指向它的nativeElement - 例如:

<input type="text" example>

@Directive({
  selector: '[example]'
})
export class ExampleDirective {    

  constructor( private el: ElementRef) {}

  ngAfterViewInit() {
    console.log(this.el.nativeElement); // the input
  }
}
Run Code Online (Sandbox Code Playgroud)

但是使用结构指令,它指向模板注释 - 例如.

<input type="text" *example>

@Directive({
  selector: '[example]'
})
export class ExampleDirective {

  constructor(
    private el: ElementRef,
    private view: ViewContainerRef,
    private template: TemplateRef<any>
  ) {}

  ngAfterViewInit() {
    this.view.createEmbeddedView(this.template);

    console.log(this.el.nativeElement); // template bindings comment
    // how to find the input itself?
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过使用ViewContainerRef,TemplateRef,@ ContentChild,@ ViewChild的各种组合 - 只是似乎无法找到输入元素本身......

Gün*_*uer 8

所有结构指令都添加到<template>元素中.Angular从不<template>向DOM 添加元素.因此,不可能将元素添加到结构指令中.

如果您使用简写的语法与*

<div *ngIf="..."></div>
Run Code Online (Sandbox Code Playgroud)

角度创造

<template [ngIf]="...">
  <div></div>
</template>
Run Code Online (Sandbox Code Playgroud)

并且因为<template>没有添加,所以无法获取它,因为<div>不是结构指令添加到您的元素也不能使用指令引用获取此元素.