结构指令-查找放置在其上的元素 [英] Structural directive - finding the element it is placed on

查看:77
本文介绍了结构指令-查找放置在其上的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用结构化指令,我如何掌握该指令所处的(本机)元素? 使用普通指令,ElementRef会指向它的nativeElement-例如:

With a structural directive, how would I get a hold of the (native) element the directive is on? With a normal directive, the ElementRef has it's nativeElement pointing to it - eg:

<input type="text" example>

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

  constructor( private el: ElementRef) {}

  ngAfterViewInit() {
    console.log(this.el.nativeElement); // the input
  }
}

但是具有结构性指令,它指向模板注释-例如.

But with a structural directive, it points to the template comment - eg.

<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?
  }
}

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

I've tried using various combinations of ViewContainerRef, TemplateRef, @ContentChild, @ViewChild - just don't seem to be able to find the input element itself...

推荐答案

所有结构指令均添加到<ng-template>元素中. Angular从不将<ng-template>元素添加到DOM.因此,不可能获得添加结构指令的元素.

All structural directives are added to <ng-template> elements. Angular never adds <ng-template> elements to the DOM. Therefore it's not possible to get the element a structural directive is added to.

如果您将速记语法与*一起使用

If you use the shorthand syntax with * like

<div *ngIf="..."></div>

角度创建

<ng-template [ngIf]="...">
  <div></div>
</ng-template>

并且由于未添加<ng-template>,因此无法获取它,并且由于<div>不是添加结构指令的元素,因此也无法使用指令引用来获取此元素.

and because <ng-template> is not added, there is no way of getting it and because <div> is not the element the structural directive is added to you also can't get this element using the directive reference.

这篇关于结构指令-查找放置在其上的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆